In this post, we will see how to print an array in PHP.

There are several ways to print contents of an array in PHP:

The most common method to print the contents of an array is using the print_r() function, which displays the human information about a variable. For an array, the values are displayed in a format that shows keys and elements.

The following code demonstrates this by printing an associative array using the print_r() function.

Download  Run Code

 
Here’s how the output would look like for a normal array,

Download  Run Code

 
Note that you can capture the output of the print_r() function by setting the second parameter to true. Now the print_r() function will return the output rather than printing it.

Download  Run Code

2. Using var_export() function

The var_export() function outputs or returns a parsable string representation of a variable, which is valid PHP code. It is often used by programmers to print an array in PHP.

Download  Run Code

 
Here’s how the output would look like for a normal array,

Download  Run Code

3. Using var_dump() function

Another good solution to dump information about the contents of an array is using the var_dump() function. For an array, it recursively displays structured information about it such as its data type, value, and length.

The following code demonstrates this:

Download  Run Code

 
Here’s how the output would look like for a normal array,

Download  Run Code

4. Using json_encode() function

The json_encode() function returns a string containing the JSON representation of a value. It can be used to encode an array in PHP, resulting in a human-readable JSON string.

Here’s how the output would look like for an associative array,

Download  Run Code

 
For a normal array, only the values are displayed.

Download  Run Code

5. Using foreach construct

Finally, you can use the foreach construct to iterate over arrays.

The following code demonstrates this, where it assigns the value of the current element to $value on each iteration:

Download  Run Code

 
The following code additionally assigns the current element’s key to the $key variable on each iteration.

Download  Run Code

 
Note: The whitespace is not preserved in the DOM, rather a single space is rendered in a browser. The solution is to wrap the output of the above functions inside a <pre></pre> tag.

That’s all about printing an array in PHP.