elbatron elbatron - 7 months ago 40
PHP Question

Basic implode foreach

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);
?>

Answer

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:

<?php
$array = get_field('casts');
$new_array = array();
foreach($array as $sub_array) {
    foreach($sub_array as $value) {
        // this array_push() function adds $value to the end of $new_array.
        array_push($new_array, $value);
    }
}
echo implode(", ", $new_array);
?>

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.

Comments