Search code examples
phparraysarray-unset

Unsetting several indexes starting with a predetermined prefix


I have an array that looks like this:

Array ( [game.info.campaign.end_date] => 2016-07-31, [game.info.campaign.start_date] => 2016-07-11, [game.info.campaign.peak_date] => 2016-07-21, [game.info.campaign.promo] => 'pokemon_go' );

I would like to unset all of them in a few line without repeating code. Is there a way to do this in PHP?

if (array_key_exists('game.info.campaign.end_date', $result)) {
    unset($result['game.info.campaign.end_date']);
}

I am doing the above right now, but there's too much repetition and some arrays have thousands of entries that start with the same prefix.


Solution

  • This should work for a given prefix. Just foreach over the array and unset keys that start with $prefix.

    $prefix = 'game.info.campaign';
    $l = strlen($prefix);
    
    foreach ($array as $key => $value) {
        if (substr($key, 0, $l) == $prefix) {
            unset($array[$key]);
        }
    }
    

    Or, if you don't mind making a new array rather than unsetting keys in your original array, using array_filter with the ARRAY_FILTER_USE_KEY option (available in PHP 5.6+) will be much faster (3-5X in my tests).

    $new = array_filter($array, function ($key) use ($prefix) {
        return strpos($key, $prefix) !== 0;
    }, ARRAY_FILTER_USE_KEY);