Osa
Osa

Reputation: 1990

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?

Upvotes: 0

Views: 224

Answers (2)

mario
mario

Reputation: 145492

Instead of runnig explode once or twice, a regex can split up the input at once, and assert the structure at it:

 preg_match_all('/
         ^         # line start
         (\w+)     # One, Two, ...
         \s+       # spaces
         (\w+)     # Four_xxxxx
         $         # line end
      /smix',
      $input,
      $array
 );
 print_r($array);

Will give you:

[0] => Array
    (
        [0] => One One_x
        [1] => Two Two_xx
        [2] => Three Three_xxx
        [3] => Four Four_xxxx
    )

[1] => Array
    (
        [0] => One
        [1] => Two
        [2] => Three
        [3] => Four
    )

[2] => Array
    (
        [0] => One_x
        [1] => Two_xx
        [2] => Three_xxx
        [3] => Four_xxxx
    )

One could also use PREG_SET_ORDER or even extract the trailing _xxxx (?)numbers.

Upvotes: 1

Kakawait
Kakawait

Reputation: 4029

$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

Upvotes: 3

Related Questions