Posted: July 25th, 2009 | Author: amos | Filed under: server | Tags: class 10, domain, hosting, registration | No Comments »
As we discussed in class, registering a website domain (e.g. registering a name such as “onepotcooking.com”) is a different transaction from hosting a website (i.e. renting space on a server where you can put your files).
However, most web hosting companies also throw in a single domain registration as a freebie for signing up for one of their web hosting plans. Plus, I have a promo code here that you can use to get further discounts from Dreamhost.
The Dreamhost promo code I am posting here will get you $20 off of a pre-paid monthly plan, and $40 off of a pre-paid yearly plan. I get a nice bonus by referring you, so although I think this is a pretty great discount for you, I also benefit by promoting it. It’s a good deal all around, but obviously you should still compare prices with others like StartLogic, GoDaddy, etc. There is no lack of competition in this market.
The Dreamhost promo code is:
WEBDEVSUMMER09
Probably the best selling point is that your own setup will be almost identical to what we used in class, since onepotcooking.com is hosted on the cheapest basic Dreamhost shared hosting plan.
I find it to be no-nonsense, well set up, relatively open, and with a very straightforward control panel that allows you to easily create and manage databases, email addresses, one-click installation of many pieces of common software such as WordPress and others, and few restrictions on usage. But it does have its ups and downs like any other hosting provider. I am not personally as familiar with the equivalent plans at other hosting companies, but I assume they all offer the same basic functionality.
Posted: July 24th, 2009 | Author: amos | Filed under: assignments | Tags: class 10, final projects, students | No Comments »
Here are the links to the final projects completed in the summer course. Please send me any additions and/or corrections.
Posted: July 23rd, 2009 | Author: amos | Filed under: search, server | Tags: class 10, privacy, robots | No Comments »
We have talked a bit about SEO and optimizing your site to be indexed by the major search engines in searches for particular keywords. We generally, but not always, want to make it easy for search engines to figure out what any given page is about. So it only seems appropriate that we should discuss the opposite procedure: how to prevent search engines from indexing your site.
The major search engines, run by Google, Yahoo, and Microsoft, send out spiders, which are automated programs that crawl the web in search of websites. Every page on every website a spider encounters is analyzed, categorized, and logged in a giant database. That database is what is used when someone does a search on a search engine for a particular term. If your site has been categorized as being related to that term, your site will show up in the search results on the search engine’s website.
Before any of the major search engines’ spiders index the contents of your site, they will look for a file on your web server called robots.txt. If you want to prevent the search engines from indexing your site and mentioning it in their search results, you should create a robots.txt file and upload it to the root folder of your website.
To prevent spiders from indexing the entire site, put this code into your robots.txt file:
User-agent: *
Disallow: /
To prevent spiders from indexing only the subdirectory called “private”, put the following code in your robots.txt file:
User-agent: *
Disallow: /private/
To prevent spiders from indexing both the “private” folder, and another folder called “my_stuff”, use a robots.txt file with the following code:
User-agent: *
Disallow: /private/
Disallow: /my_stuff/
And so on. You can repeat the “Disallow” command with as many folders as you want to keep private.
For more information about robots.txt,check out The Web Robots Pages.
Posted: July 22nd, 2009 | Author: amos | Filed under: mysql, search | Tags: class 9 | No Comments »
A few of you may be interested in adding search functionality to your sites. Unfortunately, creating a really good search is something that is far beyond the scope of this course.
However, there are a few simple options: using MySQL’s built-in search features, and using Google Search on your site.
Using MySQL to do search
I have written a post outlining the built-in search features available in MySQL. It is obvious but nevertheless important to note that in order to use MySQL’s search features, you need to have all the searchable data on your site stored in MySQL tables.
Using Google Custom Search
Google Custom Search is relatively easy to add to your page, and does not require you to be using MySQL. You simply copy and paste some code that google generates for you when you sign up for the service. This is clearly an advantage, since it will make your entire site searchable, not just those pages that use MySQL. However, there are two disadvantages: The search bar is branded with the Google logo, and when a user performs a search, they are taken to Google’s web site, which means they are taken away from your website. Click here to see an example of Google Custom Search in action.
Posted: July 22nd, 2009 | Author: amos | Filed under: php, server | Tags: class 8 | No Comments »
Some sites allow users to upload files to the server. Most often, this is the case for sites that allow users to upload images. But the same technique is used regardless of the type of file. Uploading files of any type, be they images, audio files, video files, text files, or any other type, is a singular process.
This example shows how to allow users to upload files to the server. As with any site, it all starts with the XHTML. Click here to see this example code in action.
An XHTML page with a form
When uploading files to the server, it is absolutely necessary to give the <form> tag an extra attribute: enctype=”multipart/form-data”. This tells the server that it should expect to receive not only text in the form data, but also possibly a file as well. Omitting this extra attribute is a common mistake.
Here is an example XHTML page with a file upload form on it. We’ll call it “index.html“. The especially relevant bits for this example are the <form> tag, and the <input type=”file”> tag:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>File Upload Example</title>
<link rel="stylesheet" type="text/css" href="styles/main.css" />
</head>
<body>
<div id="container">
<h1>File Upload Example</h1>
<p>Please upload an image:</p>
<form action="process_file.php" method="POST" enctype="multipart/form-data">
<input type="file" name="uploadfile">
<br /><br />
<input type="submit" value="Upload!">
</form>
</div><!-- end container -->
</body>
</html>
When the user clicks the submit button, the data entered into the form is sent along with an HTTP POST request to the server for the script, “process_file.php”. This we surmise from the “method” and “action” attributes of the <form> tag.
A PHP script to process the uploaded file
The following code is from “process_file.php“, which is the PHP script that receives the data passed along with the HTTP POST request, and decides what to do with it.
<?php
require_once("Uploader.class.php");
//create a new instance of the Uploader class
//the constructor function for the Uploader class takes three parameters: the "name" attribute of the <input type="file" name="..."> field, the subdirectory where you want to store the files, and the maximum file size allowed
$uploader = new Uploader("uploadfile", "files", "10M");
//try to do the upload
if ($uploader->upload()) {
//it worked... so get the new location of the file from the $uploader->getPermanentPath() function
$path = $uploader->getPermanentPath();
//redirect to success page, and pass the new path along
header("Location: success.php?path=" . urlencode($path));
}
else {
//it didnt work! so get the new error message from the $uploader->getError() function
$error = $uploader->getError();
//redirect to failure page, and pass the error message along
header("Location: failure.php?error=" . urlencode($error));
}
?>
Let’s analyze this file. The first thing we do is require the inclusion of another file, named “Uploader.class.php”. This file is an object-oriented bit of PHP code that I have written. This Uploader class file contains the code that does the dirty work of file uploading.
The nice thing about object oriented code is that it is built to be taken for granted (click here if you’re interested in a brief intro to object-oriented concepts.) This is one of the core philosophies of object-oriented coding: different processes should run independently of one another, and the internal workings of each process should not matter to the functioning of the other processes. This is known as “encapsulation”. So in this case, I will not explain how this class works. The code is well commented if you want to look for yourselves. I will just describe how it should be used.
Once we have included the Uploader class file, we create an Uploader object. To do so requires passing three pieces of data to the Uploader “constructor function” (read here for a brief intro to how to do object-oriented programming in PHP)
$uploader = new Uploader("uploadfile", "files", "10M");
- The first parameter is the value we gave the “name” attribute of the <input type=”file” name=”…” /> tag in the XHTML form, in this case it is “uploadfile”.
- The second parameter is the subdirectory on the server where we want to store any uploaded files… you’ll see on the server that we have set up a “files” subdirectory in this project folder. (Note: This folder must allow web browsers to write data to it. You can use a file-transfer program such as WinSCP or Cyberduck to make sure the permissions for this folder allow “Others” to “Write” to it. Usually this can be done by right-clicking on the folder in WinSCP, or Control-clicking on the folder in CyberDuck, and selecting the “Properties” or “Info” menu in WinSCP and CyberDuck respectively)

Control-click menu in Cyberduck

Info menu in CyberDuck - make sure "Others" can "Write"
- The last parameter is an option maximum file size that you want to allow users to upload, in this case 10M.
Now that the object is set up, we try to do the upload, and we test to see if it worked or not.
if ($uploader->upload()) {
//... it worked ...
}
else {
//... it failed ...
}
If the upload was successful, we redirect the browser to a “success.php” confirmation page. We also pass along the path of the newly uploaded file on the server to the success.php script.
If the upoad failed, we redirect the browser to a “failure.php” page that explains that an error occurred, and we pass along an error message as part of the request for that failure.php script.
The success confirmation page
The success.php confirmation page simply shows a user-friendly message indicating that the upload was successful. The PHP script on this page retrieves the data that was passed along with the HTTP GET request for the page. This data is the path of the newly uploaded image file on the server. The script on this page uses that path as the “src” attribute of an <img> on the page, which makes the uploaded image appear on the page.
<?php echo "<?" ?>xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Success! File Uploaded</title>
<link rel="stylesheet" type="text/css" href="styles/main.css" />
</head>
<body>
<div id="container">
<h1>Success! File Uploaded</h1>
<p>Thanks. Your image has been successfully uploaded to <?php echo $_REQUEST['path'] ?></p>
<a href="<?php echo $_REQUEST['path']; ?>">
<img src="<?php echo $_REQUEST['path'] ?>" />
</a>
</div><!-- end container -->
</body>
</html>
The failure error page
The failure.php error page simply shows a user-friendly error message indicating that the upload was unsuccessful. The PHP script on this page retrieves the data that was passed along with the HTTP GET request for the page. This data is the error message that was output by the Uploader object.
<?php echo "<?" ?>xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Failure! File Not Uploaded</title>
<link rel="stylesheet" type="text/css" href="styles/main.css" />
</head>
<body>
<div id="container">
<h1>Failure! File Not Uploaded</h1>
<p>Your image failed to upload</p>
<p><?php echo $_REQUEST['error'] ?></p>
<p>
<a href="index.html">try again</a>
</p>
</div><!-- end container -->
</body>
</html>
Posted: July 21st, 2009 | Author: amos | Filed under: email, php | Tags: class 8 | 1 Comment »
PHP’s built-in mail() function allows you to send emails from PHP code. This can be useful when, for example, you want to include a “Contact Me” form on your website, and you want an email to be sent to you whenever someone fills out that form.
The mail() function has three required parameters: the “To” email address, the subject of the message, and the content of the message. There is also a fourth additional header that can contain one or more additional information, such as who the message is “From”, any “CC” or “Bcc” email address, and some other obscure things.
Click here to view this example code in action.
XHTML page with form
In this example, we’ll look at the most common scenario: how to use an XHTML form that a user can fill in to send a message with all four parameters, “To”, “From”, subject, and message content.
The first thing to do would be set up an XHTML document called “index.html” with a form that users can fill in to send the email. A typical “Contact us” XHTML document might look like this:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Contact us</title>
<link rel="stylesheet" type="text/css" href="styles/main.css" />
</head>
<body>
<div id="container">
<h1>Contact us</h1>
<p>Fill out this form, and click submit, and we'll receive an email!</p>
<form action="process_email.php" method="POST">
<label for="name">Your Name:</label>
<input type="text" id="name" name="name"/>
<br />
<label for="email">Your Email:</label>
<input type="text" id="email" name="email"/>
<br />
<label for="subject">Subject:</label>
<input type="text" id="subject" name="subject"/>
<br />
<label for="message">Message:</label>
<textarea id="message" name="message"></textarea>
<br />
<input type="submit" value="Send email!"/>
<br />
</form>
</div><!-- end container -->
</body>
</html>
As you can probably notice from the attributes of the <form> tag, this form will be using the HTTP POST method of passing data to the server. And when a user clicks submit, the data the user entered gets sent, along with the POST request, to the file called “process_email.php”.
PHP script to process the data entered in the XHTML form
The PHP script that receives this data, called “process_email.php“, looks like the following:
<?php
$to = "yourname@yourdomain.com"; //the email address where you want to receive these emails//get the data the user entered in the form
$name = $_REQUEST['name']; //get the data the user entered in the name field and store it in a variable
$email = $_REQUEST['email']; //get the data the user entered in the email field and store it in a variable
$subject = $_REQUEST['subject']; //get the data the user entered in the subject field and store it in a variable
$message = $_REQUEST['message']; //get the data the user entered in the message field and store it in a variable
//put together the email headers, which contain the name, email, and other info about the mail program we're using
$phpVersion = phpversion(); //this calls a built-in PHP function that returns the current version of PHP installed
$headers = <<<END
From: {$name} <{$email}>
Reply-To: {$email}
X-Mailer: PHP/{$phpVersion}
END;
//use php's built-in mail() function to send this e-mail
mail($to, $subject, $message, $headers);
//redirect to success page
header("Location: success.php?to={$to}");
?>
Let’s analyze this file. You can see that the first thing this code does is hard-code the “To” address. Since these emails are supposed to all be going to us, we don’t want to ask the users of our site to enter in the email address to which they want to send these emails. We don’t want to give them the ability to send emails to anyone but us! So we hard-code that address.
The other variables we set up are all just storing the data the user entered on the XHTML page in the form. We access that data by reading it from PHP’s built-in $_REQUEST array, which has all the information on all data that was submitted along with any type of HTTP request.
Then we assemble a set of extra headers that indicate who the email is “From”, what address the receiving email program should use as the “Reply-to” address, and the name of the program that was used to send this email (in this case, we’re simply substituting the version of PHP).
Finally, we call the mail() function of PHP, along with the parameters necessary to actually send the email. Once that is finished, we redirect the user’s browser to the page, success.php, which has a user-friendly confirmation message. We redirect the browser by sending a “Location” HTTP header to the browser in response to the browser’s request for this page. This tells the browser that it should redirect to success.php, rather than stay on the current page.
The header we send to the browser in response to its request for this page looks like this:
header("Location: success.php?to={$to}");
You may recognize that we are attaching some data onto the query string of the file that we are instructing the browser to request instead of the current page. So when the browser requests that other file, it will pass some data back to that other server script along with the new request. To be exact, the browser will request the following file from the server with the following query string:
sucess.php?to=yourname@yourdomain.com
In this case, the data being passed is the “To” address indicating to where the email was sent.
Confirmation screen
The confirmation page, called “success.php“, receives that data in the $_REQUEST array, and outputs a friendly message that acknowledges the successful sending of the email to that address that was passed along with the request.
<?php echo "<?" ?>xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Success! Email Sent</title>
<link rel="stylesheet" type="text/css" href="styles/main.css" />
</head>
<body>
<div id="container">
<h1>Success! Email Sent</h1>
<p>Your email has been successfully sent to <?php echo $_REQUEST['to'] ?></p>
<p><a href="index.html">Click here to send another</a></p>
</div><!-- end container -->
</body>
</html>
Posted: July 21st, 2009 | Author: amos | Filed under: cms | Tags: class 9 | 2 Comments »
Many of you are building portfolio sites for your final projects. Many portfolio sites share the same requirements and constraints, so I encourage you to exchange information about sites you like, and techniques you’re using on your blogs for all to see.
A number of Content Management Systems (CMS’s) that claim to make the design and development of portfolio sites as painless as possible. CMS’s generally make it possible for developers to publish content on the web without writing any code.
Some CMS companies will host the website for you.
Be warned: regardless of what they claim, learning any CMS requires significant time and energy – sometimes an equivalent amount as learning to code from scratch. So unless the out-of-the-box CMS looks exactly like what you wanted it to look like, or provides features you would never be able to do on your own, just beware that you will probably need to learn the intricate details of each of these CMS’s before you can adequately customize it to suit your own site design.
Portfolio-specific CMSs
With that warning, here are some popular CMS’s that have been recommended to me for use with portfolio sites. They all come with default themes that create decent-looking sites with no coding. Each of these CMS’s should have either a demo or examples of real live sites that use them. If nothing else, browsing through the examples linked from these sites may help you brainstorm what you want your own portfolio site to look like:
General purpose CMSs
In addition, each of the major multi-purpose PHP-based CMS’s can be customized to be suitable for a portfolio site. These are the most popular CMS’s, and they might be overkill for a simple site that just requires a few pages. However, each allows you to install plugins or add-ons that add functionality that might be useful for such a site:
Hosting of CMS sites
CMS portfolio companies like CarbonMade, CargoCollective, Weebly, Wix, and others combine CMSs with hosting plans. Basically, they offer you the CMS software for free so long as you host your site on their servers. Often, this means you have to pay a monthly or yearly subscription fee for hosting to these companies. Generally, these fees are significantly higher than you would normally pay for regular website hosting from a regular domain hosting company who is not in the business of selling CMSs.
Examples
Some of these CMSs are available for you to toy with on our server. This means that we are hosting these CMSs on our own server. See this post for details about how to access these CMS installations.
Posted: July 21st, 2009 | Author: amos | Filed under: mysql | Tags: class 8 | No Comments »
Here are some posts that attempt to elucidate the concepts behind working with databases.
Intro to Relational Databases – the concepts behind databases, tables, rows, and fields
Administering MySQL using phpMyAdmin – another post explaining how to use phpMyAdmin to manage your tables
Select Statements in MySQL – reading data from databases can be more sophisticated than simply pulling all the data from a specific table. This post explains some of the finer techniques of reading from a table.
Debugging PHP and MySQL - some tips on how to figure out where any errors are coming from
Making Timestamps User-Friendly – the “created” field in all of our tables in the database stores the date a row was entered into the table. This post explains how to output those dates in a user-friendly way.
Pagination in PHP – when you pull lots of data from the database, you often will not want to display it all on one page. This post explains the concepts behind breaking up the set of results onto multiple pages. It’s a little advanced at this point, but if you’re brave…
Posted: July 21st, 2009 | Author: amos | Filed under: mysql | Tags: class 8 | No Comments »
For our assignment today, we will need to set up a table in the database where the information about all the products in our e-commerce site will be stored. This post outlines the steps necessary to create a table in the database.
All administration of databases for our class will be handled through phpMyAdmin, a web-based database administrative tool written in PHP and published for free by an altruistic development team. phpMyAdmin allows us to easily do common database tasks using a (relatively) intuitive graphical interface.
The first thing we will be doing is setting up a table in the database. Database servers can hold more than one database. To create a table in the database, we need to first select which database we want to use. On the left side of phpMyAdmin, select “classdb”: this is the database for this class.

Select database
Selecting the database will bring up a list of all the tables that already exist in that database. At the bottom of this list, you will see a space in which we can create a new table on database “classdb”. Enter in the name of your table, and the number of fields it will hold. The name should be your first initial followed by your last name, followed by an underscore, followed by the name you want to give the table. So, for example, my table would be “abloomberg_products”. The number of fields in this example is 5.

Create new table
Once we click “Go”, we are brought to a page that asks us to indicate what fields we would like the table to have, and what type of data will be stored in these fields.
- For any table we ever make, the first field will always be called “id”, and will be of type “Integer”, and have an extra property called “auto_increment”. It will also be selected as being the “Primary Key”.
- Likewise, all tables we make will have the last field named “created”, which will be of type “Timestamp”, and will have the CURRENT_TIMESTAMP checkbox selected.
The other fields that go between “id” and “created” will depend upon the table. In this case, they are:
- “title” of type “Varchar” – this will hold the title of any products in our table
- “description” of type “Text”, and length 255 – this will hold the description of any products in our table
- “price” of type “Float” – this will hold the price of any products in our table
Make sure your table has the same settings as the following:

Set fields for new table
Once you click “Save”, you should see your table name show up in the left navigation area in phpMyAdmin:

Verify new table created
If you click the tab named “Structure”, you will see the structure of the table you just created. Yours should look like this:

Table structure
If you click the tab named “Insert”, you will be able to insert a few rows into this table. Type the following two rows of data, and click the “Go” button. Notice that we are leaving the “id” field blank – the id for any row will be automatically created because we selected the “auto_increment” extra when we created the table.

Insert new rows into table
At any time, you can browse the rows you have stored in your table by clicking the “Browse” tab. This will show you a paginated list of data that is stored in the table.

Browse existing rows in table
The “SQL” tab allows you to run arbitrary SQL commands on the table. This is an example of asking for the database to show you a list of all the data in the table:
SELECT * FROM abloomberg_products WHERE 1

Run SELECT query on table
And this is an example of inserting a new row into the table:
INSERT INTO abloomberg_products (title, description, price) VALUES ('Another great cookie', 'This one has ginger schnapps in the mix', 7.49)

Run INSERT query on table
The following is how you would update an existing row in the table:
UPDATE abloomberg_products SET title='Dark Chocolate Cake', description='Only the finest 85% cocoa goes into each hand-made cake.', price=19.99 WHERE id=1

Run UPDATE query on table
And this shows how you would delete a row from the table, depending on the value stored in its id field:
DELETE FROM abloomberg_products WHERE id=1

Run DELETE query on table
Posted: July 19th, 2009 | Author: amos | Filed under: php | Tags: class 7 | No Comments »
When we learned how to create and use Javascript variables, and Javascript functions, we were learning techniques that apply across many programming languages. Fortunately, in this regard, Javascript and PHP are very similar, and we will not have to re-learn the theory of variables and functions. We will just focus on the slight differences between the syntax of the two languages.
PHP variables
In PHP, variables are declared and defined like this:
$someVariable1 = 10;
$someVariable2 = "something";
Notice the dollar sign before the name of each variable – in PHP all variable names begin with the dollar sign. Also notice that, like Javascript, all PHP instructions must end in a semi-colon.
Variables do not need to be explicitly declared in PHP. Whereas in Javascript, we declared variables, as in “var someVariable”, before using them, in PHP, we usually just define them. PHP automatically handles the declaration. There are some circumstances in which we may want to declare our intention to use a variable in PHP without actually giving it a defined value. Doing so is as simple as:
$someVariable1;
Like Javascript, PHP is a mostly untyped language, meaning a single type of variable can hold the any type of data: numeric values, Strings (i.e., text), arrays (i.e. lists), and other more complicated types of data (i.e. objects.)
PHP functions
Functions in PHP look almost identical to their Javascript counterparts. A simple function definition might look like:
function doSomething() {
echo "Hello World";
}
To call this function, one would use the following code:
doSomething();
This function would simply output the text “Hello World”. “echo” is a special PHP command to output some text.
Parameters in functions must use the PHP syntax for variable names, meaning they must begin with a dollar sign. For example, here is a function that accepts a parameter:
function sayHello($personName) {
echo "Hello, " . $personName;
}
This function takes one parameter, which it calls $personName. It then concatenates the text, “Hello, ” with the value of the variable $personName. Unlike Javascript, PHP does not use the “+” sign to do string concatenation. In PHP, “+” is used only for mathematical addition. PHP uses the concatenation operator to concatenate strings. So, for example, calling the function like this…
sayHello("Andy");
…would put the word, “Andy” in the variable called $personName. The function then concatenates the text, “Hello, ” with the word “Andy”. And ultimately, the function would output the following text:
Hello, Andy
PHP arrays
The built-in array() function of PHP is used to create arrays. Recall that arrays are lists of things, not single values like regular variables.
To create an empty array which can be populated with data later in the code, call the array() function with no parameters.
$arrSomething = array();
To add an element to the array at index 15, use code such as:
$arrSomething[15] = "the sixteenth value in the array";
To add an element to the array at the next available index, simply leave the index blank, as in the following code:
$arrSomething[] = "the new value";
To output the value of the 16th item in the array (remember that arrays are indexed starting from number 0, so the 16th item actually has an index value of 15):
echo $arrSomething[15];
In our example, that statement will output the following text, since that is what we stored earlier at index 15 of the array:
the sixteenth value in the array
PHP associative arrays
PHP arrays, like Javascript arrays, can be indexed by either integers or Strings. When they are indexed by Strings, they are often called “associative arrays”. To create an element in an array indexed by a String, use code like this:
$arrSomething["my_birthday"] = "October 3".
To output the value of this item of the array later in the code:
echo $arrSomething["my_birthday"];
This will output the following text:
October 3
PHP multidimensional arrays
PHP, being a loosely-typed language, allows you to put anything you want into a variable. Variables can contain numbers, strings, objects, or any other data type. Arrays are the same. Array elements can hold numbers, strings, objects, and other data types including other arrays.
$myArray = array();
$myArray[] = 100; //array element 0 holds the number 100
$myArray[] = "some text"; // array element 1 now holds the string, "some text"
$myArray[] = array(); //array element 2 now holds an empty array
$myArray[] = array("this", "that", "the other"); //array element 3 now holds an array with three elements in it
echo $myArray[0]; //outputs the number, 100
echo $myArray[1]; //outputs the text, "some text"
echo $myArray[2]; //outputs the text, "Array"... this is probably not what you wanted.
echo $myArray[3]; //outputs the text, "Array"... this is probably not what you wanted.
echo $myArray[3][0]; //outputs the text, "this"
echo $myArray[3][1]; //outputs the text, "that"
echo $myArray[3][2]; //outputs the text, "the other"