remove a key-value pair from a map in php

To remove a key-value pair from a map or array in PHP, you can use the unset() function, passing in the key that you want to remove.

Here's an example:

main.php
$map = array(
    'key1' => 'value1',
    'key2' => 'value2',
    'key3' => 'value3'
);

// Remove the key-value pair with key2:
unset($map['key2']);

// The map now looks like this:
// array(
//     'key1' => 'value1',
//     'key3' => 'value3'
// );
252 chars
15 lines

Alternatively, you can use the array_filter() function to create a new array that excludes the key you want to remove:

main.php
$map = array(
    'key1' => 'value1',
    'key2' => 'value2',
    'key3' => 'value3'
);

// Remove the key-value pair with key2:
$map = array_filter($map, function($key) {
    return $key !== 'key2';
}, ARRAY_FILTER_USE_KEY);

// The map now looks like this:
// array(
//     'key1' => 'value1',
//     'key3' => 'value3'
// );
328 chars
17 lines

Both approaches will remove the specified key-value pair from the map.

related categories

gistlibby LogSnag