split a map into two maps in php

To split a map or associative array into two maps based on some condition-say a condition on keys or values of the map-you can use the array_filter function along with a foreach loop. Here's an example code:

main.php
<?php
// the original map
$original_map = array(
    'apple' => 2,
    'banana' => 4,
    'orange' => 6,
    'mango' => 8
);

// split the map based on a condition on keys
$condition = function ($key){
    return ($key == 'orange' || $key == 'mango');
};
$map1 = array_filter($original_map, $condition, ARRAY_FILTER_USE_KEY);
$map2 = array_filter($original_map, function($key) use ($condition) { return !$condition($key); }, ARRAY_FILTER_USE_KEY);

// display the two maps
print_r($map1);
print_r($map2);
?>
508 chars
21 lines

In this example, we split the original map $original_map into two maps based on a condition on keys. The condition states that elements with keys 'orange' and 'mango' will go to $map1 and the rest will go to $map2.

To apply a condition on values, you can modify the condition function and use ARRAY_FILTER_USE_BOTH flag instead of ARRAY_FILTER_USE_KEY.

related categories

gistlibby LogSnag