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.
- You want to print only one array element value
- You want to print all of the PHP array values
- You want to print the complete array with keys, values maybe data types
Code:
// Create a new array
$colorList2[] = "red";
$colorList2[] = "green";
$colorList2[] = "blue";
$colorList2[] = "black";
$colorList2[] = "white";
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:
echo $colorList2[0];
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:
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:
$colorList2[220] = "yellow";
$colorList2["apple"] = "apple-green";
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:
foreach ($colorList2 as $value) {
echo $value."";
}
However if you want to display the keys as well you can write your code in the following format:
Code:
foreach ($colorList2 as $key => $value) {
echo $key." - ".$value."";
}
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:
No comments:
Post a Comment