PHP array tutorial

Posted by admin on December-11-2009 Add Comments

Bookmark and Share


In this tutorial I will show you how to work with arrays in PHP. You will learn how to create, sort or print an array. Besides this we will touch on multidimensional arrays as well.

Step 1 – Introduction to arrays

Arrays are special data types. Despite of other normal variables an array can store more than one value. Let’s suppose you want to store basic colors in your PHP script. You can construct a small list from them like this:

Color list:

  • red
  • green
  • blue
  • balck
  • white

It is quite hard, boring, and bad idea to store each color in a separate variable. It would be very nice to have the above representation almost as it is in PHP. And here comes array into play.

The array type exists exactly for such purposes. So let’s see how to create an array to store our color list.

Step 2 – Creating an array

There are more ways to create an array in PHP. Maybe the most easiest way to create our color list array is the following:

PHP Code:
$colorList = array("red","green","blue","black","white");

n other sollution is to initialise array elements one-by-one as follows:

PHP Code:
$colorList[0] = "red";
$colorList[1] = "green";
$colorList[2] = "blue";
$colorList[3] = "black";
$colorList[4] = "white";

If you don’t want to bother about numbering – I will explain it later
you can create your array as this:

PHP Code:
$colorList[] = "red";
$colorList[] = "green";
$colorList[] = "blue";
$colorList[] = "black";
$colorList[] = "white";

As you can see this is almost similar to the other but here we didn’t write any number between the square brackets. In this case PHP makes the numbering internally from 0 to 4. This function is the so called auto-incremented keys.

Step 3 – Display the array content

In the last step we have created an array. It is not important which sollution you choose the result is the same. It’s nice but how you can use the data in the array. For example how to display the elements? There are more ways to do this. Let’s see the possibilities.

If you want only display one element of the array then you can just write the following code:

PHP Code:
echo $colorList[0];

This code will display the text “red”. However you may want to display all elements in the array. You can write a loop and display them like this:

PHP Code:
for ($i=0;$i<=4;$i++){
echo
$colorList[$i];
}

It is quite easy. However it is not the best sollution as the number of element is hard coded. There is a much better way to display all elements of an array. You can use a foreach loop as this:

PHP Code:
foreach ($colorList as $value) {
echo
$value;
}

If you want to display array content for debugging purposes then you can use 2 built in PHP functions. These are the print_r and var_dump. These functions displays tha array as key-value pairs. Besides this var_dump also displays variable informations. You can use them as follows:

PHP Code:
print_r($colorList);
echo
"";
var_dump($colorList);

In the next step we will learn about associative arrays.

Step 4 – Associative arrays

In general PHP arrays are maps, which means that it is a type that maps values to keys. In our example it means that where the key is 0 there the value is “red” and where the key is 1 there the value is “green“. However you have the possibility to use more meaningful keys. Associative array means that you can assign an arbitray key to every value. Associative arrays are sometimes referred to as dictionaries. Our colorList array can be defined as associative array like this:

PHP Code:
$colorList = array("apple"=>"red",
"grass"=>"green",
"sky"=>"blue",
"night"=>"black",
"wall"=>"white");

You have to remember that array keys are case-sensitive, but type insensitive. It means that ‘a’ differs from ‘A’ but ‘1′ is the same as 1.
So, the array above can be defined (created) one-by-one elements like this:

PHP Code:
$colorList["apple"] = "red";
$colorList["grass"] = "green";
$colorList["sky"] = "blue";
$colorList["night"] = "black";
$colorList["wall"] = "white";

And you can display the content similar to the normal array, but here you need to use the string value instead of the number.

PHP Code:
echo "The sky is ".$colorList["sky"]." and the grass is ".$colorList["grass"];

You can mix your array and use numbers and strings in the same list like this:

PHP Code:
$colorList["apple"] = "red";
$colorList[5] = "green";
$colorList["sky"] = "blue";
$colorList["night"] = "black";
$colorList[22] = "white";

As you can see even the numbers can be any so you don’t have to make it continous. However be aware of using such mixed arrays as it can result errors.

In the next step we will discuss some usefull array functions.

Step 5 – Multidimensional arrays

As each element value of the array can be any type it means that it can be other array as well. If an array element value is an other array then this is a multidimensional array. Of course the internal array values can be arrays as well and so on. You can define 10 dimensional (or more) array if you want.

Creating a multidimensional array is as almost simple as the normal array. Let’s see an example:

PHP Code:
$myLists['colors'] = array("apple"=>"red",
"grass"=>"green",
"sky"=>"blue",
"night"=>"black",
"wall"=>"white");
$myLists['cars'] = array("BMW"=>"M6",
"Mercedes"=>"E 270 CDI",
"Lexus"=>"IS 220d",
"Mazda"=>"6",
"Toyota"=>"Avensis");

To acces and display an element in the multidimensional array you just extend the key list as follows:

PHP Code:
echo $myLists['cars']['Toyota'];

Of course you can define normal, mixed and associative multidimensional arrays.

As last step I will show you some usefull array handling function on the next page.

Step 6 – Array functions

During programming it can be neccessary to manipulate arrays. Do do this PHP has some usefull built in functions.

Get the length of the array, or with other words how many elements are in the array. To get this information you can use the sizeof function. It tells you how big is the actual data. You can use it like this:

PHP Code:
echo sizeof($colorList);

Sometimes you want to remove an element from the array. In this case you can use the unset function like this:

PHP Code:
unset($colorList["sky"]);

To check whether an array has a requested element you can use the isset function as follows:

PHP Code:
if (isset($colorList["grass"])) echo "OK";

And last you sometimes want to sort your array for eaxmple to display its content in alphabetical order. To do this you have more possibilities. There are more built in array sorting functions in PHP. The most known are sort and asort. The difference between them is that sort renumbers the keys so you will lost the key values. So if you need the key names (associative arrays) use the asort function.
You can use them as follows:

PHP Code:
asort($colorList);
sort($colorList);

Both of the functions sorts values in ascending order. If you want to sort them descending use the corresponding rsort and arsort functions.

On the last page you will find a complete example code which demonstrates array handling.

Step 7 – Complete example code

This is an array demonstartion code:

PHP Code:
// Creating an array
$colorList = array("apple"=>"red",
"grass"=>"green",
"sky"=>"blue",
"night"=>"black",
"wall"=>"white");

//Display array item
echo "The sky is ".$colorList["sky"]." and the grass is ".$colorList["grass"];

// Display array size
echo "The array size is: ".sizeof($colorList);

// Remove one element from the array
unset($colorList["sky"]);
echo
"The new array size is: ".sizeof($colorList);

echo "";

// Check the existence of an element
if (isset($colorList["grass"])) echo "grass key is present";
else echo
"grass key is not present";

if (isset($colorList["sky"])) echo "sky key is present";
else echo
"sky key is not present";

// Display the complete array content
echo "Array before sorting:";
print_r($colorList);
// Display the complete array content after sorting
echo "Array after asort:";
print_r (asort($colorList));
echo
"Array after sort:";
print_r (sort($colorList));

// Creating a multidimensional array
$myLists['colors'] = array("apple"=>"red",
"grass"=>"green",
"sky"=>"blue",
"night"=>"black",
"wall"=>"white");

$myLists['cars'] = array("BMW"=>"M6",
"Mercedes"=>"E 270 CDI",
"Lexus"=>"IS 220d",
"Mazda"=>"6",
"Toyota"=>"Avensis");

// Display an item from the array
echo "A demo item is:".$myLists['cars']['Toyota'];

// Create a new array
$colorList2[] = "red";
$colorList2[] = "green";
$colorList2[] = "blue";
$colorList2[] = "black";
$colorList2[] = "white";

// DUmp it's content
echo "Dump colorList2 with print_r:<br/>";
print_r($colorList2);
echo
"Dump colorList2 with var_dump:<br/>";
var_dump($colorList2);
echo
"";

// Display array elements from loop
echo "Array content:<br/>";
for (
$i=0;$i<=4;$i++){
echo
$colorList2[$i]."";
}
// Display array elements with foreach
echo "Array content:";
foreach (
$colorList2 as $value) {
echo
$value."<br/>";
}
?>

Post a Comment

You must be logged in to post a comment.