0

I've got the following array, containing ordered but non consecutive numerical keys:

Array
(
    [4] => 2
    [5] => 3
    [6] => 1
    [7] => 2
    [8] => 1
    [9] => 1
    [10] => 1
)

I need to split the array into 2 arrays, the first array containing the keys below 5, and the other array consisting of the keys 5 and above. Please note that the keys may vary (e.g. 1,3,5,10), therefore I cannot use array_slice since I don't know the offset.

Do you know any simple function to accomplish this, without the need of using a foreach ?

1
  • You should really specify if you need to keep the original keys or not. Commented Jun 27, 2014 at 11:45

2 Answers 2

3

Just found out array_slice has a preserve_keys parameter.

$a = [
    4 => 2,
    5 => 3,
    6 => 1,
    7 => 2,
    8 => 1,
    9 => 1,
    10 => 1
];

$desired_slice_key = 5;
$slice_position = array_search($desired_slice_key, array_keys($a));

$a1 = array_slice($a, 0, $slice_position, true);
$a2 = array_slice($a, $slice_position, count($a), true);
Sign up to request clarification or add additional context in comments.

5 Comments

This seems like it would be more complex than foreach. Can you show the simple solution you're describing?
Yeah, you're right. Just wrote the code and it's far from simple.
But it's pretty short using the preserve_keys parameter added in 5.0.2
Note that this answer assumes that the original array is sorted by the keys.
Yes it does. But specifically writing "5 and above" pretty much tells us they are.
0

you could use array_walk, passing in the arrays you wish to add the keys to by reference using the use keyword - something along the lines of this should work:

$splitArray = [1 => 2, 3 => 1, 5 => 2, 7 => 1, 9 => 3, 10 => 1];

$lt5 = [];
$gt5 = [];

array_walk($splitArray, function(&$val, $key) use (&$lt5, &$gt5) {
    $key < 5 ? $lt5[] = $key : $gt5[] = $key;
});

var_dump($lt5, $gt5);

Comments

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.