Suppose I have an array of data like this:
array:2 [
0 => array:2 [
"id" => 7539
"os" => "Android"
]
1 => array:2 [
"id" => 7540
"os" => "iOS"
]
]
I want to grab the id values only and place them in a variable that’s comma separated (i.e $var = "7539,7540";) using a foreach() loop but for some reason – my code below outputs just the first value in an array (not an individual value).
How can I fix this so that both values are comma separated in a separate variable?
$var = "";
foreach($dataSet as $data) {
$var = explode(",", $data['id']);
}
dd($var);
Output:
array:1 [
0 => "7539"
]
>Solution :
Your current code doesn’t work because you are setting $var on each iteration of the foreach. You can use string concatenation however arrays can be a bit more concise and give you the opportunity to re-use the data:
$ids = array(); //emtpy array to hold the values
foreach($dataSet as $data) {
$ids[] = $data['id']; //append the `id` to the array
}
$var = implode(',', $ids); //join the ids into a string with a comma as the separator
This can also be done using array_column if you don’t need to loop:
$var = implode(',', array_column($dataSet, 'id')); //7539,7540
Here is a working example: https://3v4l.org/WNMLX