Home > Software engineering >  Separate info from an array with to make a comma separated string
Separate info from an array with to make a comma separated string

Time:12-26

I want to make a string separated by a comma. Example : test, sdf

Array ( 
[0] => Array ( [name] => Test [0] => Test ) 
[1] => Array ( [name] => sdf [0] => sdf ) )


$List = implode(', ', $Array);


Return : Notice: Array to string conversion

CodePudding user response:

Extract the list of arrays into another array, then perform the implode

Demo

<?php
$Array=[];

$temparray= ["name" => "Test" ];
array_push($Array,$temparray );

$temparray= ["name" => "sdf" ];
array_push($Array,$temparray );

//print_r($Array);

foreach($Array as $key=>$value) {
$newarray[]=$value["name"];
}
$List = implode(', ', $newarray);
var_dump($List);
?>

CodePudding user response:

You can try this. With the help of array function you can do it very easily.

$array = [
        ["name" => 'Test', 0 => 'Test'], 
        ["name" => 'sdf', 0 => 'sdf']
    ];

echo $str = implode(',', array_map(function($el){ return $el['name']; }, $array));

O/P :

Test,sdf
  • Related