1

Exist some simple function for count only the integer keys of an array?

for example i have this array:

0 => "string"
1 => "string"
"#aaa" => "string"

I need count only the first two element without using a custom foreach loop.

3
  • 1
    By 'count' do you mean add/sum or include only integer-based keys? Commented Apr 3, 2014 at 22:01
  • with count i mean a numeric count of the only integer-based keys, so for this example the result is 2. Commented Apr 3, 2014 at 22:04
  • possible duplicate of PHP: How to use array_filter() to filter array keys? Commented Apr 3, 2014 at 22:04

3 Answers 3

2

To count the integer keys, try

count(array_filter(array_keys($array), function($key) {
    return is_int($key);
}));
Sign up to request clarification or add additional context in comments.

Comments

2

Here's a simple solution:

$int_keys = count(array_filter(array_keys($arr), 'is_int'));

Comments

1

Do a check on each key to loop through only the numbered keys:

foreach( $arr as $key => $value ) {
    if( is_numeric($key) ) { //Only numbered keys will pass
        //Do whatever you want
    }
}

2 Comments

Technically, OP only wants to match integer keys. is_numeric will match decimal numbers too
Sure, I guess it all depends on OP's implementation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.