Home >Backend Development >PHP Tutorial >How Can I Effectively Print the Contents of a Nested Array in PHP?
When working with arrays in PHP, it can be helpful to echo or print their contents. However, you may encounter issues when trying to display the array as a flat list. Let's explore how to resolve this issue.
Consider the following array structure:
$results = [ 'data' => [ [ 'page_id' => 204725966262837, 'type' => 'WEBSITE', ], [ 'page_id' => 163703342377960, 'type' => 'COMMUNITY', ], ], ];
If you attempt to echo the array contents using a foreach loop, the output will include the nested array structure:
foreach ($results as $result) { echo $result->type; echo "<br>"; }
This will result in the following output:
WEBSITE <br> COMMUNITY <br>
To display the array contents as a flat list, you can use the following methods:
1. print_r()
Print the array using print_r(). For a more visually appealing output, you can enclose it with
tags:</p> <pre class="brush:php;toolbar:false">echo '<pre class="brush:php;toolbar:false">'; print_r($results); echo '';
2. var_dump()
Use var_dump() to display additional information about the array, including data types and lengths:
var_dump($results);
3. foreach() with Direct Access
You can iterate over the array and directly access the desired values, such as the type property:
foreach ($results['data'] as $result) { echo $result['type']; echo "<br>"; }
This will produce the desired output:
WEBSITE <br> COMMUNITY <br>
The above is the detailed content of How Can I Effectively Print the Contents of a Nested Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!