Search code examples
phparraysexplodedelimited

Split each value of a flat array at delimiter and create separate arrays from each half


I'm trying to explode and separate the results in 2 different arrays

One One_x
Two Two_xx
Three Three_xxx
Four Four_xxxx

I first want to explode the break line ( \n )..
then explode the space to come up with all One, Two, Three, Four in an array
AND One_x, Two_xx, Three_xxx, Four_xxxx in a different array

i tried to explode the break line

$ex = explode("\n", $numbers);

then

foreach ($ex as $number) {
  $ex = explode(" ", $number);
}

but it seems a bit confusing to me.

How to solve this?


Solution

  • $array1 = array();
    $array2 = array();
    foreach($ex as $number){
      $tmp = explode(" ", $number);
      $array1[] = $tmp[0];
      $array2[] = $tmp[1];
    }
    

    Simplest way I think

    EDIT: care you set $ex in loop ... Not a good idea. Use another var