PHP - split array by key -
i've got following array, containing ordered non consecutive numerical keys:
array ( [4] => 2 [5] => 3 [6] => 1 [7] => 2 [8] => 1 [9] => 1 [10] => 1 )
i need split array 2 arrays, first array containing keys below 5, , other array consisting of keys 5 , above. please note keys may vary (e.g. 1,3,5,10), therefore cannot use array_slice
since don't know offset.
do know simple function accomplish this, without need of using foreach
?
just found out array_slice
has 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);
Comments
Post a Comment