Remove all elements of an array with non-numeric keys
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.