问题
I have an array that looks something like this:
Array
(
[0] => apple
["b"] => banana
[3] => cow
["wrench"] => duck
)
I want to take that array and use array_filter or something similar to remove elements with non-numeric keys and receive the follwoing array:
Array
(
[0] => apple
[3] => cow
)
I was thinking about this, and I could not think of a way to do this because array_filter does not provide my function with the key, and array_walk cannot modify array structure (talked about in the PHP manual).
回答1:
Using a foreach loop would be appropriate in this case:
foreach ($arr as $key => $value) {
if (!is_int($key)) {
unset($arr[$key]);
}
}
回答2:
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_filterworks with values,array_keysfirst creates a new array with the keys as values (ignoring the original values).- These are then filtered by the
is_numericfunction.- The result is then flipped back so the keys are keys once again.
- Finally,
array_intersect_keyonly 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.
回答3:
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);
回答4:
Here's a loop:
foreach($arr as $key => $value) {
if($key !== 0 and !intval($key)) {
unset($arr[$key]);
}
}
来源:https://stackoverflow.com/questions/11042536/remove-all-elements-of-an-array-with-non-numeric-keys