Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How'd I populate a variable with a comma separated string that comes from foreach loop?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading