Skip to content
Advertisement

Explode/Implode in foreach loop

I have a list of strings like

$list = "foo, bar";

I use explode on this list to get the list items as an array:

$strings = explode(", ", $list);

Now I need to take each item of the array and pass it to an API one by one and the API will return the IDs for the list entries. I want to end up with a string that is just like $list but with the IDs instead of the strings. My problem is that I can’t pass an array to the API funtion. I need to do it for every single list item. So I’m looping through the array:

foreach($strings as $names){
    $ID = $o_api->GetGroupIdsByName($s_token, $names)->getData();
    $AssignedGroups = implode("", $ID).";";        
    echo $AssignedGroups;
    }

If I run this code the result is: 3;4; Which is exactly what I need to pass it to another API function. But when I need to re-use this list outside of the loop . If I then use $AssignedGroups I only get the last ID, not the 2 (or more) merged ones.

What am I doing wrong?

Here is the complete code for reference:

 $Groups = explode(", ", $value["Groups"]);
    //var_dump($Groups);
    foreach($Groups as $Names){
    $GroupIDs = $o_api->GetGroupIdsByName($s_token, $Names)->getData();       
    $AssignedGroups = implode("", $GroupIDs).";";        
    echo $AssignedGroups;

}
    $o_api->CreateUser($s_token, $Login, $Password, $IsOfflineUser, $IsWindowsUser, $FirstName, $LastName, $AssignedGroups, $Ratings);

Advertisement

Answer

What really should be done here:

$Groups = explode(", ", $value["Groups"]);
//var_dump($Groups);

// init as empty array
$AssignedGroups = [];
foreach ($Groups as $Names) {
    $GroupIDs = $o_api->GetGroupIdsByName($s_token, $Names)->getData();       
    // a new string to array
    $AssignedGroups[] = implode(';', $GroupIDs);
}

// here you can implode again:
$AssignedGroups = implode(';', $AssignedGroups);
// or even with another delimiter
$AssignedGroups = implode(',', $AssignedGroups);

Fiddle with implode example.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement