- Instant help with your Php coding problems

PHP Array tutorial

Introduction to arrays

Arrays are special data types. Despite 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
  • black
  • white

It is quite a 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.

Creating an array

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

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

Another solution is to initialize array elements one-by-one as follows:

$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 like this:

$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.

Display the array content

In the last step, we have created an array. It is not important which solution 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:

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:

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

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

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 display the array as key-value pairs. Besides this var_dump also displays variable information. You can use them as follows:

print_r($colorList);
echo "";
var_dump($colorList);

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 arbitrary key to every value. Associative arrays are sometimes referred to as dictionaries. Our colorList array can be defined as an associative array like this:

$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:

$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.

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 as this:

$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 continuous. However, be aware of using such mixed arrays as it can result in errors.

Multidimensional arrays

As each element value of the array can be any type it means that it can be another array as well. If an array element value is another 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:

$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 access and display an element in the multidimensional array you just extend the key list as follows:

echo $myLists['cars']['Toyota'];

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

Array functions

During programming, it can be necessary to manipulate arrays. To do this PHP has some useful built-in functions.

Get the length of the array, or in 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:

echo sizeof($colorList);

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

unset($colorList["sky"]);

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

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

And last you sometimes want to sort your array for example 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 lose the key values. So if you need the key names (associative arrays) use the asort function.
You can use them as follows:

asort($colorList);
sort($colorList);

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

Complete example code

This is an array demonstration code:

<?php
    // 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 "<br/>";
 
   // 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/>";
   }
?>

 

Share "PHP Array tutorial" with your friends