0

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.

  • 1
    By 'count' do you mean add/sum or include only integer-based keys? – sbeliv01 Apr 03 '14 at 22:01
  • with count i mean a numeric count of the only integer-based keys, so for this example the result is 2. –  Apr 03 '14 at 22:04
  • possible duplicate of [PHP: How to use array\_filter() to filter array keys?](http://stackoverflow.com/questions/4260086/php-how-to-use-array-filter-to-filter-array-keys) – Sunny Patel Apr 03 '14 at 22:04

3 Answers3

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
    }
}
Sunny Patel
  • 7,830
  • 2
  • 31
  • 46
1

To count the integer keys, try

count(array_filter(array_keys($array), function($key) {
    return is_int($key);
}));
Phil
  • 157,677
  • 23
  • 242
  • 245
1

Here's a simple solution:

$int_keys = count(array_filter(array_keys($arr), 'is_int'));
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331