Saturday, August 16, 2008

PHP print array

Arrays are very usefull data types in PHP. Besides this they are very flexible as well. In PHP there are more ways how to print array content. Regarding what information you want to display we can make some categories.

  1. You want to print only one array element value
  2. You want to print all of the PHP array values
  3. You want to print the complete array with keys, values maybe data types
Before we print array content let's create a small array to work with.

Code:

  1. // Create a new array

  2. $colorList2[] = "red";

  3. $colorList2[] = "green";

  4. $colorList2[] = "blue";

  5. $colorList2[] = "black";

  6. $colorList2[] = "white";

PHP F1



Ok, now as we have the array let's see how to print it's content. First if you want to display only one value from the array you can use it as a normal variable in the following way:



Code:

  1. echo $colorList2[0];

PHP F1



Don't forget to use the correct key index as if you use the array name without key then it will print only the text "Array" as the actual variable type is array. However if you define a wrong key you will print nothing.

The following examples demonstartes some wrong usage:



Code:

  1. echo $colorList2;

  2. echo $colorList2[220];

  3. echo $colorList2["apple"];

PHP F1



However the code in the 2. and 3. line should be ok, if the array have such elements. So if you extend your array as follows then the last 2 statement will print valid values.



Code:

  1. $colorList2[220] = "yellow";

  2. $colorList2["apple"] = "apple-green";

PHP F1



 



The other most frequently used php print array method is when you want to display all values from an array. Using our colorList example array you can create a loop to display all values. Here you have more possibilities but PHP has a special loop for this purpose. It is called foreach. With foreach you can visit all elements in a loop and display its value, key or both if you want. The most simplest code example looks like this:



Code:

  1. foreach ($colorList2 as $value) {

  2. echo $value."";

  3. }

PHP F1



However if you want to display the keys as well you can write your code in the following format:



Code:

  1. foreach ($colorList2 as $key => $value) {

  2. echo $key." - ".$value."";

  3. }

PHP F1



Print array for debugging purpose

Finally I will show you how to print the complete array content with a single function call. PHP has 2 built in functions to display a complete array. They are the print_r and the var_dump. Both are doing the same but var_dump gives you a little bit more information. It displays not only key and values but variable types as well.


However the usage are similar:



Code:

  1. echo "Dump colorList2 with print_r";

  2. print_r($colorList2);

  3. echo "Dump colorList2 with var_dump";

  4. var_dump($colorList2);

PHP F1

No comments: