0

I have a php array with each value in array having a space delimiter like

a[1]="1 32"
a[2]="2 33"
a[3]="3 67"
...

I want to divide this array into 2 arrays using the delimiter space. Result should be something like:

a[1]="1"
a[2]="2"
a[3]="3"
...
b[1]="32"
b[2]="33"
b[3]="67"
...

What should be the optimal way to go about this?

4
  • You may consider using this: php.net/split and have it store first value at array a[i], and second in b[i]... Consider (i) to be your position in the array in case you insert at random times. (I was just advised that this is out of commission so you may not want to use this) Commented Dec 25, 2013 at 18:45
  • @LJ-C split is deprecated, it should not be used anymore. This function has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged. Commented Dec 25, 2013 at 18:47
  • Or maybe preg_split Commented Dec 25, 2013 at 18:48
  • @user689: I would say preg_split() is overkill for something simple as this. Commented Dec 25, 2013 at 18:49

3 Answers 3

1

Loop through your array, use explode() to split each value with space as the delimiter, and push them to separate arrays:

$arr1 = array();
$arr2 = array();

foreach ($array as $value) {
    list($a, $b) = explode(' ', $value);
    $arr1[] = $a;
    $arr2[] = $b;
}

Demo.

Sign up to request clarification or add additional context in comments.

Comments

1

My take with array_walk():

<?php

$input = [
    "1 32",
    "2 33",
    "3 67"
];

$array1 = [];
$array2 = [];

array_walk($input, function ($item) use (&$array1, &$array2) {
        $temp = explode(' ', $item);
        $array1[] = $temp[0];
        $array2[] = $temp[1];
    }
);

print_r($array1);
print_r($array2);

Note: The syntax assumes PHP 5.4. Demo.

Comments

-1

You may use explode http://www.php.net/explode

Eg. explode(" ", $a[1]);

2 Comments

He wants elements in two different arrays a[] and b[] you are putting them in one array.
I was only trying to show a basic use of the explode function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.