2

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.

Jonathan Lam
  • 16,831
  • 17
  • 68
  • 94
dms
  • 129
  • 1
  • 1
  • 8

2 Answers2

1

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);
Don't Panic
  • 41,125
  • 10
  • 61
  • 80
1

If the prefix is game.info.campaign, then you can loop over them and delete those with matching keys:

foreach($result as $key => $val)
    if(strpos($key, "game.info.campaign") === 0)
        unset($result[$key]);

This checks if the $key begins with "game.info.campaign" using PHP strpos() and unsets them.

See a live demo.

Jonathan Lam
  • 16,831
  • 17
  • 68
  • 94