Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
1  
By 'count' do you mean add/sum or include only integer-based keys? –  sbeliv01 2 days ago
1  
loop, is_int() –  Dagon 2 days ago
    
with count i mean a numeric count of the only integer-based keys, so for this example the result is 2. –  hans 2 days ago
    
possible duplicate of PHP: How to use array_filter() to filter array keys? –  LaughDonor 2 days ago
add comment

3 Answers

up vote 1 down vote accepted

To count the integer keys, try

count(array_filter(array_keys($array), function($key) {
    return is_int($key);
}));
share|improve this answer
add comment

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
    }
}
share|improve this answer
    
Technically, OP only wants to match integer keys. is_numeric will match decimal numbers too –  Phil 2 days ago
    
Sure, I guess it all depends on OP's implementation. –  LaughDonor 2 days ago
add comment

Here's a simple solution:

$int_keys = count(array_filter(array_keys($arr), 'is_int'));
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.