Search code examples
phparraysunset

How to unset when only knowing a key's numerical order


I'm wanting to unset from an array but I only know each key by it's numerical order.

What's the best way to remove them?

$arr = [
    'horse' => true,
    'rabbit' => false,
    'cat' => true,
    'dog' => false,
    'sheep' => false,
];

$remove = [0,1,3];

Desired result:

$arr = [
    'cat' => true,
    'sheep' => false,
];

Solution

  • Use array_keys to get the actual keys, then use the indexes to get the corresponding keys.

    $arr_keys = array_keys($arr);
    foreach ($remove as $r) {
        unset($arr[$arr_keys[$r]]);
    }