I have the following code of which I want to echo array elements separated by commas. The code outputs the disered list, but without commas. What am I missing?
<?php
$array = get_field('casts');
$elements = $array;
foreach($array as $key => $value) {
echo implode(', ', $value)};
?>
EDIT 1: where $elements
are nested arrays.
EDIT 2: Working snippet:
<?php
$array = get_field('casts');
$new_array = array();
foreach($array as $sub_array) {
foreach($sub_array as $value) {
array_push($new_array, $value);
}
}
echo implode(", ", $new_array);
?>
Why are you assigning
$elements = $array;
and then never using$elements
?Also you don't need to loop (
foreach
) to implode an array.Try this:
Here is the documentation on
implode()
You can play around and test the above code here.
Also next time, add the tag
php
, otherwise our codes won't get color syntax.