Saturday, August 16, 2008

PHP array tutorial

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.

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

Code:

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

PHP F1



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



Code:

  1. $colorList[0] = "red";

  2. $colorList[1] = "green";

  3. $colorList[2] = "blue";

  4. $colorList[3] = "black";

  5. $colorList[4] = "white";

PHP F1



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



Code:

  1. $colorList[] = "red";

  2. $colorList[] = "green";

  3. $colorList[] = "blue";

  4. $colorList[] = "black";

  5. $colorList[] = "white";

PHP F1



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.



 



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:



Code:

  1. echo $colorList[0];

PHP F1



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:



Code:

  1. for ($i=0;$i<=4;$i++){

  2. echo $colorList[$i];

  3. }

PHP F1



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:



Code:

  1. foreach ($colorList as $value) {

  2. echo $value;

  3. }

PHP F1



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:



Code:

  1. print_r($colorList);

  2. echo "";

  3. var_dump($colorList);

PHP F1



In the next step we will learn about 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:



Code:

  1. $colorList = array("apple"=>"red",

  2. "grass"=>"green",

  3. "sky"=>"blue",

  4. "night"=>"black",

  5. "wall"=>"white");

PHP F1



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:



Code:

  1. $colorList["apple"] = "red";

  2. $colorList["grass"] = "green";

  3. $colorList["sky"] = "blue";

  4. $colorList["night"] = "black";

  5. $colorList["wall"] = "white";

PHP F1



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



Code:

  1. echo "The sky is ".$colorList["sky"]

  2. ." and the grass is ".$colorList["grass"];

PHP F1



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



Code:

  1. $colorList["apple"] = "red";

  2. $colorList[5] = "green";

  3. $colorList["sky"] = "blue";

  4. $colorList["night"] = "black";

  5. $colorList[22] = "white";

PHP F1



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.



 



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:



Code:

  1. $myLists['colors'] = array("apple"=>"red",

  2. "grass"=>"green",

  3. "sky"=>"blue",

  4. "night"=>"black",

  5. "wall"=>"white");

  6. $myLists['cars'] = array("BMW"=>"M6",

  7. "Mercedes"=>"E 270 CDI",

  8. "Lexus"=>"IS 220d",

  9. "Mazda"=>"6",

  10. "Toyota"=>"Avensis");

PHP F1



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



Code:

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

PHP F1



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



 



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:



Code:

  1. echo sizeof($colorList);

PHP F1



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



Code:

  1. unset($colorList["sky"]);

PHP F1



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



Code:

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

PHP F1



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:



Code:

  1. asort($colorList);

  2. sort($colorList);

PHP F1



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



 



This is an array demonstartion code:



Code:

  1. // Creating an array

  2. $colorList = array("apple"=>"red",

  3. "grass"=>"green",

  4. "sky"=>"blue",

  5. "night"=>"black",

  6. "wall"=>"white");

  7. //Display array item

  8. echo "The sky is ".$colorList["sky"]

  9. ." and the grass is ".$colorList["grass"];

  10. // Display array size

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

  12. // Remove one element from the array

  13. unset($colorList["sky"]);

  14. echo "The new array size is: ".sizeof($colorList);

  15. echo "";

  16. // Check the existence of an element

  17. if (isset($colorList["grass"])) echo "grass key is present";

  18. else echo "grass key is not present";

  19. if (isset($colorList["sky"])) echo "sky key is present";

  20. else echo "sky key is not present";

  21. // Display the complete array content

  22. echo "Array before sorting:";

  23. print_r($colorList);

  24. // Display the complete array content after sorting

  25. echo "Array after asort:";

  26. print_r (asort($colorList));

  27. echo "Array after sort:";

  28. print_r (sort($colorList));

  29. // Creating a multidimensional array

  30. $myLists['colors'] = array("apple"=>"red",

  31. "grass"=>"green",

  32. "sky"=>"blue",

  33. "night"=>"black",

  34. "wall"=>"white");

  35. $myLists['cars'] = array("BMW"=>"M6",

  36. "Mercedes"=>"E 270 CDI",

  37. "Lexus"=>"IS 220d",

  38. "Mazda"=>"6",

  39. "Toyota"=>"Avensis");

  40. // Display an item from the array

  41. echo "A demo item is:".$myLists['cars']['Toyota'];

  42. // Create a new array

  43. $colorList2[] = "red";

  44. $colorList2[] = "green";

  45. $colorList2[] = "blue";

  46. $colorList2[] = "black";

  47. $colorList2[] = "white";

  48. // DUmp it's content

  49. echo "Dump colorList2 with print_r:<br/>";

  50. print_r($colorList2);

  51. echo "Dump colorList2 with var_dump:<br/>";

  52. var_dump($colorList2);

  53. echo "";

  54. // Display array elements from loop

  55. echo "Array content:<br/>";

  56. for ($i=0;$i<=4;$i++){

  57. echo $colorList2[$i]."";

  58. }

  59. // Display array elements with foreach

  60. echo "Array content:";

  61. foreach ($colorList2 as $value) {

  62. echo $value."<br/>";

  63. }

  64. ?>

No comments: