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?
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.”