I’m working with a nested array in PHP and I’m trying to figure out the cleanest way to display its values. Right now, when I dump the array, I get the full structure with keys and nested levels, but that’s not what I want to show.
What I’m aiming for is to php echo array values directly for example, just printing specific fields like type from each item without all the extra array formatting.
$items = [
'data' => [
[
'page_id' => 204725966262837,
'type' => 'WEBSITE'
],
[
'page_id' => 163703342377960,
'type' => 'COMMUNITY'
]
]
];
I tried looping through the array like this:
foreach ($items['data'] as $entry) {
echo $entry['type'] . "<br>";
}
This works for some cases, but I’m wondering if this is the recommended way to echo array values in PHP, or if there’s a cleaner or more flexible approach to output array contents without displaying the entire structure.
Any tips or best practices would be appreciated!
What you’re doing with the foreach loop is actually the most common and clear way to just display specific values from an array. For example:
foreach ($items['data'] as $entry) {
echo $entry['type'] . "<br>";
}
``
I use this all the time when I only need certain fields, like type in your example. It’s easy to read, maintain, and you don’t risk printing unnecessary details or nested structures. Personally, for simple arrays, this is my go-to method.
From my experience, if your array has a consistent structure, array_column can make it even cleaner. It extracts a single column of values from a multidimensional array:
$types = array_column($items['data'], 'type');
foreach ($types as $type) {
echo $type . "<br>";
}
This way, you don’t even have to deal with nested loops, and it reads nicely. I’ve found this super handy when working with larger arrays or when you want to quickly extract one field without iterating through everything manually.
Sometimes, you just want a quick, inline list without the
tags or extra formatting. In those cases, combining array_column with implode works really well:
echo implode(", ", array_column($items['data'], 'type'));
Output:
WEBSITE, COMMUNITY
I often use this approach when printing summaries or logs where readability matters more than HTML formatting. It’s clean, concise, and avoids dumping the entire array structure.
In short: looping with foreach is the most straightforward and flexible, array_column is great for extracting a single field cleanly, and implode helps for quick, compact display. Personally, I switch between these depending on whether I want a detailed display or a simple inline output.