A Big Mistake
Fruity Pizza
Eating Italian
Push And Pull
Looping the Loop
What’s That Noise?
Music for the Masses
A Big Mistake
Having spent lots of time travelling around
the outer landscape of PHP – learning all about control
structures, operators and variables – you’re
probably bored. You might even be thinking of dropping out right
now, and instead spending your time more
constructively (or so you think) in front of the idiot box.
That would be a big mistake. And when I say
big, I mean humongous.
You see, if you forego this segment of the tutorial for the dubious
charms of Ally McBeal, you’re going to miss out on one of PHP’s coolest
variable types. It’s a little thing called an array, and I’m not
exaggerating when I tell you that once you’re on speaking terms with
it, you’re never going to look at a PHP script the same way again. But
hey, don’t take my word for it… toss that remote aside and come see
for yourself!
Fruity Pizza
Thus far, the variables we’ve discussed contained only a
single value, such as:
<?php
$i = 5;
?>
However, array variables are a different kettle of fish altogether.
An array is a complex variable that allows you to store multiple values
in a single variable (which
is handy when you need to store and represent
related information). Think of the array
variable as a “container”
variable, which can contain one or more values. For example:
<?php
// define an array
$pizzaToppings = array('onion', 'tomato', 'cheese', 'anchovies', 'ham', 'pepperoni');
print_r($pizzaToppings);
?>
Here, $pizzaToppings is an array variable, which contains the values
'onion', 'tomato', 'cheese', 'anchovies', 'ham' and 'pepperoni'.
(Array variables
are particularly useful for grouping related values together.)
print_r() is a special function that allows you to take a sneak peek
inside an array. It’s more useful for debugging (finding out why your
script doesn’t work) than it is for display purposes, but I’ll use it
here so you can see what’s going on under the surface. You do have
your server running and your browser open, right?
The various elements of the array are accessed via an index number,
with the first element starting at zero. So, to access the element
'onion', you would use the notation $pizzaToppings[0], while
'anchovies' would be $pizzaToppings[3] -
essentially, the array variable name followed by the index number
enclosed within square braces.
PHP also allows you to replace indices with user-defined “keys”, in
order to create a slightly different type of array. Each key is unique,
and corresponds to a single value within the array.
<?php
// define an array
$fruits = array('red' => 'apple', 'yellow' => 'banana', 'purple' => 'plum', 'green' => 'grape');
print_r($fruits);
?>
In this case, $fruits is an array variable containing four key-value
pairs. (The => symbol is used to indicate the
association between a key and its value.) In order
to access the value 'banana', you would use the notation
$fruits['yellow'], while the value 'grape' would be accessible via the
notation $fruits['green'].
This type of array is sometimes referred to as a “hash” or
“associative array”. If you’ve ever used Perl, you’ll see
the similarities to the Perl hash variable.
Eating Italian
The
simplest was to define an array variable is the array() function.
Here’s how:
<?php
// define an array
$pasta = array('spaghetti', 'penne', 'macaroni');
?>
The rules for choosing an array variable name are the same as those
for any other PHP variable: it must begin with a letter or underscore,
and can optionally be followed by more letters, numbers and
underscores.
Alternatively, you can define an array by specifying values for each
element in the index notation, like this:
<?php
// define an array
$pasta[0] = 'spaghetti';
$pasta[1] = 'penne';
$pasta[2] = 'macaroni';
?>
If you’re someone who prefers to use keys rather than default numeric indices, you might
prefer the following example:
<?php
// define an array
$menu['breakfast'] = 'bacon and eggs';
$menu['lunch'] = 'roast beef';
$menu['dinner'] = 'lasagna';
?>
You can add elements to the array in a similar manner. For example, if you wanted to add
the element ‘green olives' to the $pizzaToppings array, you would
use something like this:
<?php
// add an element to an array
$pizzaToppings[3] = 'green olives';
?>
In order to modify an element of an array, simply assign a new value
to the corresponding scalar variable. If you wanted to replace 'ham'
with 'chicken', you’d use:
<?php
// modify an array
$pizzaToppings[4] = 'chicken';
?>
You can do the same using keys. The following statement modifies the element with
the key ‘lunch’ to a different value:
<?php
// modify an array
$menu['lunch'] = 'steak with mashed potatoes';
?>
Push And Pull
You can also add an element to the end of an existing array with the
array_push() function:
<?php
// define an array
$pasta = array('spaghetti', 'penne', 'macaroni');
// add an element to the end
array_push($pasta, 'tagliatelle');
print_r($pasta);
?>
And you can remove an element from the end of an array using the interestingly-named
array_pop() function.
<?php
// define an array
$pasta = array('spaghetti', 'penne', 'macaroni');
// remove an element from the end
array_pop($pasta);
print_r($pasta);
?>
If you need to pop an element off the top of the array, you can use
the array_shift() function:
<?php
// define an array
$pasta = array('spaghetti', 'penne', 'macaroni');
// take an element off the top
array_shift($pasta);
print_r($pasta);
?>
And the array_unshift() function
takes care of adding elements to the beginning of the array.
<?php
// define an array
$pasta = array('spaghetti', 'penne', 'macaroni');
// add an element to the beginning
array_unshift($pasta, 'tagliatelle');
print_r($pasta);
?>
The array_push() and array_unshift() functions don’t work with associative arrays; to add elements to these arrays, it’s better to use the $arr[$key] = $value notation to add new values to the array.
The explode() function splits a string into smaller components, based on a user-specified delimiter, and returns the pieces as elements as an array.
<?php
// define CSV string
$str = 'red, blue, green, yellow';
// split into individual words
$colors = explode(', ', $str);
print_r($colors);
?>
To do the reverse, you can use the implode() function, which creates
a single string from all the elements of an array by joining them
together with a user-defined delimiter. Reversing the example above, we
have:
<?php
// define array
$colors = array ('red', 'blue', 'green', 'yellow');
// join into single string with 'and'
// returns 'red and blue and green and yellow'
$str = implode(' and ', $colors);
print $str;
?>
Finally, the two examples below show how the sort() and
rsort()functions can be used to sort an array alphabetically (or
numerically), in ascending and descending order respectively:
<?php
// define an array
$pasta = array('spaghetti', 'penne', 'macaroni');
// returns the array sorted alphabetically
sort($pasta);
print_r($pasta);
print "<br />";
// returns the array sorted alphabetically in reverse
rsort($pasta);
print_r($pasta);
?>
Looping the Loop
So that takes care of putting data inside an array. Now, how about
getting it out?
Retrieving data from an array is pretty simple: all you
need to do is access the appropriate element of the array using its
index number. To read an entire array you
simply loop over it, using any of the loop constructs you learned about
in Part Three of this tutorial.
How about a quick example?
<html>
<head></head>
<body>
My favourite bands are:
<ul>
<?php
// define array
$artists = array('Metallica', 'Evanescence', 'Linkin Park', 'Guns n Roses');
// loop over it and print array elements
for ($x = 0; $x < sizeof($artists); $x++) {
echo '<li>'.$artists[$x];
}
?>
</ul>
</body>
</html>
When you run this script, here’s what you’ll see:
My favourite bands are:
- Metallica
- Evanescence
- Linkin Park
- Guns n Roses
In this case, I’ve defined an array, and then used the for() loop
to: run through it, extract the elements using
the index notation, and display them one after the other.
I’ll draw your attention here to the sizeof() function. This
function is one of the most important and commonly used array
functions. It returns
the size of (read: number of elements within) the array. It is mostly
used in loop counters to ensure that the loop iterates as many times as
there are elements in the array.
If you’re using an associative array, the array_keys() and
array_values()functions come in handy, to get a
list of all the keys and values within the array.
<?php
// define an array
$menu = array('breakfast' => 'bacon and eggs', 'lunch' => 'roast beef', 'dinner' => 'lasagna');
/* returns the array ('breakfast', 'lunch', 'dinner') with numeric indices */
$result = array_keys($menu);
print_r($result);
print "<br />";
/* returns the array ('bacon and eggs', 'roast beef', 'lasagna') with numeric indices */
$result = array_values($menu);
print_r($result);
?>
What’s That Noise?
There is, however, a simpler way of extracting all the elements of
an array. PHP 4.0 introduced a spanking-new loop type designed specifically
for the purpose of iterating over an array: the foreach() loop.
(It is similar in syntax to the Perl construct of the same name.) Here’s what it looks like:
foreach ($array as $temp) {
do this!
}
A foreach() loop runs once for each element of the array passed to
it as argument, moving forward through the array on each iteration.
Unlike a for() loop, it doesn’t need a counter or a call to
sizeof(), because it keeps track of its position in
the array automatically. On each run, the statements within the curly
braces are executed, and the currently-selected array element is made
available through a temporary loop variable.
To better understand how this works, consider this rewrite of the
previous example, using the foreach() loop:
<html>
<head></head>
<body>
My favourite bands are:
<ul>
<?php
// define array
$artists = array('Metallica', 'Evanescence', 'Linkin Park', 'Guns n Roses');
// loop over it
// print array elements
foreach ($artists as $a) {
echo '<li>'.$a;
}
?>
</ul>
</body>
</html>
Each time the loop executes, it places the currently-selected array
element in the temporary variable $a. This
variable can then be used by the statements inside the loop block.
Since a foreach() loop doesn’t need a counter to keep track of where it
is in the array, it is lower-maintenance and also much easier to
read than a standard for() loop. Oh yeah… and it also
works with associative arrays, with no extra programming needed.
Music for the Masses
In addition to their obvious uses, arrays and loops also come in
handy when processing forms in PHP. For example, if you have a group of
related checkboxes or a multi-select list, you can use an array to
capture all the selected form values in a single variable,
to
simplify processing. Consider the
following example, which illustrates this:
<html>
<head></head>
<body>
<?php
// check for submit
if (!isset($_POST['submit'])) {
// and display form
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="checkbox" name="artist[]" value="Bon Jovi">Bon Jovi
<input type="checkbox" name="artist[]" value="N'Sync">N'Sync
<input type="checkbox" name="artist[]" value="Boyzone">Boyzone
<input type="checkbox" name="artist[]" value="Britney Spears">Britney Spears
<input type="checkbox" name="artist[]" value="Jethro Tull">Jethro Tull
<input type="checkbox" name="artist[]" value="Crosby, Stills & Nash">Crosby, Stills & Nash
<input type="submit" name="submit" value="Select">
</form>
<?php
}
else {
// or display the selected artists
// use a foreach loop to read and display array elements
if (is_array($_POST['artist'])) {
echo 'You selected: <br />';
foreach ($_POST['artist'] as $a) {
echo "<i>$a</i><br />";
}
}
else {
echo 'Nothing selected';
}
}
?>
</body>
</html>
When the above form is submitted, PHP will
automatically create an array variable, and populate it with the items
selected. This array can then be processed with a foreach() loop, and
the selected items retrieved from it.
You can do this with a multi-select list also, simply by using array
notation in the select control’s “name” attribute. Try it out for
yourself and see… and make sure you tune in for
the next PHP 101 tutorial, same time, same channel.
Copyright Melonfire, 2004 (http://www.melonfire.com).
All rights reserved.




August 4, 2006 at 7:26 am
what about we want to add an element from an associative array with array_push?
September 6, 2006 at 3:56 am
I’ve just tried as I think the simpler way is this one :
<?php
// define an array
$menu = array(‘breakfast’ => ‘bacon and eggs’, ‘lunch’ => ‘roast beef’, ‘dinner’ => ‘lasagna’);
// add an element to the end
$menu['midnight meal']=’whisky’;
print_r($menu);
?>
//array_push($menu, ‘midnight meal’ => ‘whisky’); just dont work
September 27, 2006 at 11:38 am
<html>
<head></head>
<body>
<?
if(!isset($_POST['submit'])) { // Display the form
?>
<form action="<? echo $_SERVER['PHP_SELF']; ?>" method="post">
<?
$artists = array(‘George Jones’,'Alan Jackson’,'Lonestar’,'Tim McGraw’,'Kenny Chesney’,'George Strait’,'Waylon Jennings’);
sort($artists);
foreach($artists as $a)
print("<input type=’checkbox’ name=’artist[]‘ value=’$a’
>$a<br>\n");
print("<input type=’submit’ name=’submit’ value=’Select’>");
print("</form>");
} elseif(is_array($_POST['artist'])) {
print "You selected: <br />";
foreach($_POST['artist'] as $a)
print "<i>$a</i><br />";
}
else
print("Nothing selected.");
?>
</body>
</html>
August 13, 2007 at 3:20 pm
The article says:
"For example, if you wanted to add the element ‘green olives’ to the $pizzaToppings array, you would use something like this:
<?php
// add an element to an array
$pizzaToppings[3] = ‘green olives’;
?>"
But, actually should be:
$pizzaToppings[] = ‘green olives’;
Notice there nothing between the brackets. This tells PHP to add the value to the array using the next available index number (current maximum index number + 1). This is a simpler version of the "push" function.
October 24, 2007 at 1:38 pm
Hey Vikram Vaswani!
I’m programing in Delphi, and your explanations are really easy to understand! This collection was just what I needed! It was hard to transfer from forms to a all code environment. You really helped me!
Thanks a lot!!!!!!!!
<?php
$band=’Metallica’;
echo ‘PS : ‘.$band.’ being your fav band really says a lot |..|,’;
?>
December 19, 2007 at 3:24 am
I think these explanations are pretty good, i have to be honest that i have been having a hard time with php and things don’t always work the way i would like them to..
But this is a great post, it will help me a lot, and using food to explain it is probably the best way to make me understand something
Brian the <a href="http://www.ramenlicious.com">ramen noodles</a> guy
*I think it’s keep the pizzatoppings variable name for my future php web pages
March 2, 2008 at 9:00 pm
Great Tutorials, i’m learning a lot in the hope i’ll be able to tackle some simple CMS.
I have a quick question. In this example where by the artists are selected and then the results displayed. Using the previous ‘sort()’ parameter – where will this be placed in order to sort the selected list?
April 23, 2008 at 9:17 pm
If I am understanding correctly, you want to sort first the result and then you want to "echo" it.
Then, you need to add this to your code:
<code>
$temp = $_POST['artist'];
sort (temp);
</code>
and change to below:
<code>
foreach ($temp as $a)
</code>
$temp would hold the ARRAY result from artist. Then, you can perform sort (to sort alphabetically) or rsort (to do the reverse sort)
In partial code, you will have a code like this:
<code>
else {
// or display the selected artists
// use a foreach loop to read and display array elements
if (is_array($_POST['artist'])) {
echo ‘You selected: <br />’;
$temp = $_POST['artist'];
rsort (temp);
foreach ($temp as $a) {
echo "<i>$a</i><br />";
}
}
else {
echo ‘Nothing selected’;
}
}
</code>
HTH.
June 13, 2008 at 12:03 pm
A USER SAID:
——————————————————————-
The article says:
"For example, if you wanted to add the element ‘green olives’ to the $pizzaToppings array, you would use something like this:
<?php
// add an element to an array
$pizzaToppings[3] = ‘green olives’;
?>"
But, actually should be:
$pizzaToppings[] = ‘green olives’;
Notice there nothing between the brackets. This tells PHP to add the value to the array using the next available index number (current maximum index number + 1). This is a simpler version of the "push" function.
———————————————————————
Well, it is not necessary that it should be like that. $pizzaToppings[3] = ‘green olives’;
Is perfectly correct php syntax. Dont forget that these tutorials are for absolute beginners.
July 11, 2008 at 7:13 am
I found an error report when executing the code without choosing the artist,so i make some changes here,emmmmh..just like this:
<html>
<head>
<title>Your Fav Artist!</title>
</head>
<body>
<?php
//checking for submit (first isset)
if (!isset($_POST['submit'])) {
//display form
?>
<form action = "<?php echo $_SERVER['PHP_SELF']; ?>" method = "POST">
<input type="checkbox" name="artist[]" value="Bon Jovi">Bon Jovi<br />
<input type="checkbox" name="artist[]" value="N Sync">N Sync<br />
<input type="checkbox" name="artist[]" value="Boyzone">Boyzone<br />
<input type="checkbox" name="artist[]" value="Britney Spears">Britney Spears<br />
<input type="checkbox" name="artist[]" value="Jethro Tull">Jethro Tull<br />
<input type="checkbox" name="artist[]" value="Crosby, Stills & Nash">Crosby, Stills & Nash<br />
<input type = "submit" name = "submit" value = "select">
</form>
<?php
}
else {
//take the second isset
if (!isset($_POST['artist'])) {
echo "Nothing selected. <br />";
}
else {
echo ‘You selected :<br />’ ;
foreach ($_POST['artist'] as $a) {
echo "<b>$a</b> <br />";
}
}
}
?>
</body>
</html>
hope this help!
July 17, 2008 at 8:10 pm
I’ve been reading, but figured I would drop this here for my first comment: THANKS. well written, to the point. It’s stirring up all my old c++ knowledge. Perfect. I’ve been riveted since i started readin.
August 14, 2008 at 10:25 am
I noticed a previous user commented that the variable array pizzaTopping[3] was a permissable way to add an element to an array – surely this would be pizzaTopping[]?
Enjoying the tutorials – might aswell learn something when at work with nought to do
May 23, 2009 at 10:12 pm
Hate to be nitpicky, but you are leaving out closing tags for your <li>’s go back and check your code, pretty sloppy.
August 23, 2009 at 12:51 am
At last, learning php by example using practical examples. It’s been difficult learning php by looking at the savvy developer’s code that I don’t understand, and then at the beginner’s examples that use improper usage.
August 23, 2009 at 5:37 pm
Or you could do this:
<html>
<head></head>
<body>
<?php
// check for submit
if (!isset($_POST['submit']))
{
// If $_POST['submit'] does NOT exist; Load the following Form and exit the program.
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="checkbox" name="artist[]" value="Bon Jovi">Bon Jovi
<input type="checkbox" name="artist[]" value="N’Sync">N’Sync
<input type="checkbox" name="artist[]" value="Boyzone">Boyzone
<input type="checkbox" name="artist[]" value="Britney Spears">Britney Spears
<input type="checkbox" name="artist[]" value="Jethro Tull">Jethro Tull
<input type="checkbox" name="artist[]" value="Crosby, Stills & Nash">Crosby, Stills & Nash
<input type="submit" name="submit" value="Select">
</form>
<?php
} //else {
// or display the selected artists
// use a foreach loop to read and display array elements
//take the second isset
elseif (!isset($_POST['artist']))
{
echo "Nothing selected. <br />";
}
elseif (is_array($_POST['artist']))
{
echo ‘You selected: <br />’;
foreach ($_POST['artist'] as $a)
{
echo "<i>$a</i><br />";
}
}
?>
</body>
</html>
August 26, 2009 at 12:10 am
Is anyone still reading this? Still relevant tutorials 3 years later. Thanks! All was quite clear but found myself wondering…how to display the key of an associative array? Obviously displaying the count won’t work. Perhaps out of scope for beginner tutorial but I looked it up and it is a simple modification to the php4+ builtin foreach() function:
foreach ($fruits as $key => $value)
echo $key.’:’.$value.’<br />’;
Hope that helps someone. (From the tut you could extract using array_keys() too, but that would be a lot more convoluted).
August 31, 2009 at 10:14 pm
I’m trying to run the sample music for the masses code and it fails with a 500 error. It also displays:
‘; foreach ($_POST['artist'] as $a) { echo "$a
"; } } else { echo ‘Nothing selected’; } } ?>
On the page. I’m not sure what is wrong, since I copied and pasted the code. Did something change between when this was written and the current version?
Could it be that I’m on a hosted server and the hp echo $_SERVER['PHP_SELF'] won’t work?
I’m confused.
April 11, 2010 at 4:26 am
I wasn’t going to comment, mainly because I agree so wholeheartedly with others’ sentiments, but I had to create an account just to say how incredible this tutorial is so far. I am a 24 year old n00b programmer and find this tutorial equal parts educational, entertaining, fun, and funny. I realize this was written around 6 years ago but it has still helped increase my knowledge n-fold. Keep it up!
April 27, 2010 at 12:53 pm
Thank you so much! I’ve learned more about using arrays!
August 2, 2010 at 11:54 pm
Yup im a complete noob and have read a few books on PHP now, but with your examples and the way you explain things I really think im starting to understand all this stuff!
Please please please keep writing these tuts!
Cheers mate
March 30, 2011 at 4:39 am
I have read lots of book on PHP, but I always fell asleep in the
middle of the book. But when I was reading your tutorial man I was jacked into it. Your examples and thinking style made me understood the basic concept more clearly.
Thanks and keep up the good work
June 15, 2011 at 9:37 am
Just wanted to say how I think your PHP Beginner guide is very good.
Been working in PHP for a long while now, since my 2nd year at University, always going for the bigger projects, but these tutorials are good as a reminder for the basic things I sometimesm forget.
Trying to build myself up a library of howto’s and will be customising these to show what I can do.
For that single reason, I thank you alot for that!
I can’t tell you how much I appreciate it!
July 15, 2011 at 3:44 pm
First of all these tuts are fab. I’m a web designer don’t know any programming at all but want to be able to expand my skills so I may offer more to my clients. Never thought I’d have so much fun doing it! (php, js, sql… the world!)
I’ve been using your tutorials to (try to) develop a simple form evaluating program for my sisters website. It’s as much for practice as it would be an asset for her site. I keep running into walls because I want to do things that are a little beyond the scope of these tuts, like create an array from user inputed values. Can you recommend a forum, perhaps, or some further reading? Maybe someone whose writing is as skilled and clear as your own…
September 9, 2011 at 7:28 am
but i’m newly to here. on 08.09.2011, i regitered here. ohhh it’s really cool. now i something know about PHP.