phparrayscodeignitercounterundefined-index

How to increment a potentially undefined variable?


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.


Solution

  • $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);