Remove all elements of an array with non-numeric keys

白昼怎懂夜的黑 提交于 2019-12-03 00:27:29

Using a foreach loop would be appropriate in this case:

foreach ($arr as $key => $value) {
    if (!is_int($key)) {
        unset($arr[$key]);
    }
}

It can be done without writing a loop in one (long) line:

$a = array_intersect_key($a, array_flip(array_filter(array_keys($a), 'is_numeric')));

What it does:

  • Since array_filter works with values, array_keys first creates a new array with the keys as values (ignoring the original values).
  • These are then filtered by the is_numeric function.
  • The result is then flipped back so the keys are keys once again.
  • Finally, array_intersect_key only takes the items from the original array having a key in the result of the above (the numeric keys).

Don't ask me about performance though.

As of PHP 5.6, it's now possible to use array_filter in a compact form:

array_filter($array, function ($k) { return is_numeric($k); }, ARRAY_FILTER_USE_KEY);

Demo.

This approach is about 20% slower than a for loop on my box (1.61s vs. 1.31s for 1M iterations).


As of PHP 7.4, it's possible to also use short closures::

array_filter($array, fn($k) => is_numeric($k), ARRAY_FILTER_USE_KEY);

Here's a loop:

foreach($arr as $key => $value) {
    if($key !== 0 and !intval($key)) {
         unset($arr[$key]);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!