PHP print array - Print complete php arrays

Home - Tutorials - Basics

This is a small tutorial how to print array in PHP. You will learn all the way you can display, print the content of an array.

Tutorial info:

Name:PHP print array
Total steps:2

Bookmark PHP print array

Bookmark and Share

Step 2 - Print complete php arrays

PHP print array

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:

  1. foreach ($colorList2 as $value) {
  2. echo $value."";
  3. }
However if you want to display the keys as well you can write your code in the following format:
  1. foreach ($colorList2 as $key => $value) {
  2. echo $key." - ".$value."";
  3. }

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:
  1. echo "Dump colorList2 with print_r";
  2. print_r($colorList2);
  3. echo "Dump colorList2 with var_dump";
  4. var_dump($colorList2);

Previous Step of PHP print array

Tags: php print array, print array, php array, php, print, array

Follow phpf1 on Twitter

F1 Site Family
Java F1
JavaScript F1

Total time: 0.0233