Search code examples
phparraysexplodeflattendelimited

Explode all delimited strings in a flat array into a flat array of individual substrings


I have a loop that contains a string of comma seperated values.

foreach ($profiles as $profile) {
    $user_states[] = exlpode(', ', '[string of comma seperated states]');
}

The problem I'm experiencing is the $user_states array ends up being two levels, with each iteration of the loop creating a nested array.

array (size=2)
  0 => 
    array (size=3)
      0 => string 'DC' (length=2)
      1 => string 'Maryland' (length=8)
      2 => string 'Northern-Virginia' (length=17)
  1 => 
    array (size=1)
      0 => string 'North-Carolina,Virginia' (length=23)

How can I take exploded values and place them all into a single array?


Solution

  • []= operator means add to array. explode method, returns an array, so what you are doing is adding an array into array.

    since profiles probably contains 2 elements, you are getting an array of size 2 of exploded strings

    what you are probably looking for is array_merge

    replace the inner part of the loop with this:

    $exploded    = exlpode(', ', '[string of comma seperated states]');
    $user_states = array_merge($user_states, $exploded)