PHP Array tutorial - Complete example code


Home - Tutorials - Basics

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.

Tutorial info:


Name:PHP Array tutorial
Total steps:7
Category:Basics
Level:Beginner

Bookmark PHP Array tutorial



Bookmark and Share

Step 7 - Complete example code


PHP Array tutorial


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:
    "
    ;
  50. print_r($colorList2);
  51. echo "Dump colorList2 with var_dump:
    "
    ;
  52. var_dump($colorList2);
  53. echo "";
  54. // Display array elements from loop
  55. echo "Array content:
    "
    ;
  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."
    "
    ;
  63. }
  64. ?>





Previous Step of PHP Array tutorial


Tags: array, php array, sort array, create array, print array, array length



Follow phpf1 on Twitter




F1 Site Family
AJAX F1
CSS F1
Database F1
Flash F1
HTML F1
Java F1
JavaScript F1
PhotoShop F1
PHP F1
Scripts F1
Tutorial F1
Windows F1

Total time: 0.0496