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.

Looking to get a count of particular key=>values in an multi dimensional array. What I have works i.e. the result is correct, but I can't seem to get rid of the Undefined Index notice.

$total_arr = array();

foreach($data['user'] as $ar) {
     $total_arr[$ar['city']]++;
}

print_r($total_arr);

Any ideas? I have tried isset within the foreach loop, but no joy...

share|improve this question
    
Possibly related: PHP isset() function misbehaving –  Amal Murali Oct 24 '13 at 14:13

2 Answers 2

up vote 2 down vote accepted
$total_arr = array();

foreach($data['user'] as $ar) {
    if(array_key_exists($ar['city'],$total_arr) {
        $total_arr[$ar['city']]++;
    } else {
        $total_arr[$ar['city']] = 1; // Or 0 if you would like to start from 0
    }
}    

print_r($total_arr);
share|improve this answer
    
Correct answer. And if one wanted this a little bit “shorter”, one could also mis-use the ternary operator slightly, and replace the whole if/else construct with simply isset($total_arr[$ar['city']) ? $total_arr[$ar['city']++ : $total_arr[$ar['city'] = 1; –  CBroe Oct 24 '13 at 14:15
    
isset is usually always faster than array_key_exists and you'll never have to bother about NULL values here, so go with isset instead. –  h2ooooooo Oct 24 '13 at 14:15
    
Strangely enough, replacing 'array_key_exists' with 'isset' produces the same undefined index error. Thanks for the solution ogres! –  Solaris76 Oct 24 '13 at 14:23

PHP will throw that notice if your index hasn't been initialized before being manipulated. Either use the @ symbol to suppress the notice or use isset() in conjunction with a block that will initialize the index value for you.

share|improve this answer

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.