0

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"
]
miken32
  • 42,008
  • 16
  • 111
  • 154

2 Answers2

2

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

cOle2
  • 4,725
  • 1
  • 24
  • 26
0

You could do this with the implode method of Collections:

collect($dataSet)->implode('id', ',')

Or you can also use the Collection methods pluck and join:

collect($dataSet)->pluck('id')->join(',')

Laravel 8.x Docs - Collections - Available Methods - implode

Laravel 8.x Docs - Collections - Available Methods - pluck

Laravel 8.x Docs - Collections - Available Methods - join

lagbox
  • 48,571
  • 8
  • 72
  • 83
  • You may like to move your answer to the canonical target. I am doing a major clean up of "implode array column" questions. – mickmackusa Jul 26 '22 at 02:50