Considering array like:
$arr = array(
'key' => 'foo'
'key2' => 'bar',
0 => 'num_foo',
1 => 'num_bar'
);
How to extract values under 0 & 1? (Besides using for loop). Maybe any standard function do the job?
If you’re using a PHP version >= 5.6, you can use array_filter
, with the flag that tells it to pass the key to the callback function.
$arr = array(
'key' => 'foo',
'key2' => 'bar',
0 => 'num_foo',
1 => 'num_bar'
);
$new_array = array_filter($arr, function($key) {
return is_numeric($key);
}, ARRAY_FILTER_USE_KEY);
var_dump($new_array);
Edit: As Robbie pointed out, using is_numeric
is the better choice here. (Previously my example used is_int
.)
Edit 2: Perhaps is_int
is actually the better choice here. is_numeric
would return true for values such as +0123.45e6
, or hexadecimal/binary number notations as well – not sure if that’s desired.
is_int
would normally return false for a value such as '1'
. It works here, because we are dealing with arrays – and PHP automatically converts array keys to integer, if they are an “integer string.”
If you use is_int()
inside a foreach
loop it's easy enough. Try this:
foreach ($arr as $key => $value) {
if (is_int($key)) {
echo "Found integer key with value: $value
";
}
}
If you desperately want to avoid using a loop, try this:
array_walk($arr, function($val, $key) {
if (is_int($key)) {
echo "Found integer key with value: $val
";
}
});
That does, of course, use a loop internally anyway.
you can use array_filter()
to return the numeric keys
// $Your_array is your original array with numeric and string keys
// array_filter() returns an array of the numeric keys
$numerickeys = array_filter(array_keys($Your_array), function($k) {return is_int($k);});
// this is a simple case where the filter function is a plain
// built-in function requiring one argument, it can be passed as a string:
// Really, this is all that's needed:
$numerickeys = array_filter(array_keys($Your_array), 'is_int');