php implode on arrays fails with array to string conversion

This question already has an answer here:

  • Implode data from a multi-dimensional array

    5 answers

I have this

print_r($results);

contains

Array ( [0] => Array ( [item] => reverse bleeper ) 
      [1] => Array ( [item] => tyres prssure ) )

When i try

implode(',', $results)

throws an error throws an array to string conversion error

which i understand is because my structure contains array withing array

How can i implode such or create a comma separated string from such

You can foreach the array and the subarray below it and push them to an flat array.

$results = [[1],[2]];

foreach($results as $subarr) {
    Foreach($subarr as $val){
        $res[] = $val;
    }
}
Echo implode(',', $res);

Outputs:

1,2

https://3v4l.org/idgCR

try this :

if(sizeof($results) > 0) { // to prevent error if no result
    foreach($results as $key => $val) {
        $output = $val;
    }
    echo implode(',', $output);
}

Implode does not deal with multidimensional arrays,

but as a work around you may use array_walk_recursive with this:

$arr = [
    0 => ['a','b','c'],
    1 => ['d','e','f'],
];

$glue = ',';
function implode_recursive($arr, $glue) {
    array_walk_recursive($arr, function ($value, $key) use (&$string, $glue) {
        $string .= $glue . $value;
    });

    return ltrim($string, $glue);
}

echo implode_recursive($arr, $glue);

Outputs: a,b,c,d,e,f

live example: https://3v4l.org/Wqauh


this will blindly implode your array, but as mentioned in this answer if you are sure of your key name –in your case your key is item– you may use array_column instead.

in your case the solution would be :

echo implode(', ', array_column($input, 'item'));

your have this error because $results is a multidimentional array,
try this simple and clean solution:

<?php

$results = [
    ['item' => 'reverse bleeper'],
    ['item' => 'tyres prssure']
];

echo implode(', ', array_column($results, 'item'));;

output:

reverse bleeper, tyres prssure