Daniel
Daniel

Reputation: 667

PHP - split array by key

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 ?

Upvotes: 0

Views: 403

Answers (2)

Keir Lavelle
Keir Lavelle

Reputation: 523

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);

Upvotes: 0

Sergiu Paraschiv
Sergiu Paraschiv

Reputation: 10153

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);

Upvotes: 3

Related Questions