简体   繁体   中英

PHP: What is the error in the foreach loop?

I am trying to avoid using array_count_values (too slow) to count occurrences, so I am using a foreach loop but I keep getting this error message below even though the result prints correctly!!!

PHP Notice: Undefined offset: 0 in on line 5 PHP Stack trace:

$somearray=array(0,1,2,3,4,5,6,0,1,2,3,4,0,1,2);
$frequency=array();
foreach($somearray as $key => $val) {
        $frequency[$somearray[$key]]++; //THIS IS LINE 5
    }

print_r($frequency);

It prints correctly despite all thrown error messages:

Array
(
    [0] => 3
    [1] => 3
    [2] => 3
    [3] => 2
    [4] => 2
    [5] => 1
    [6] => 1
)

The notice "Undefined offset: 0" is verbose, some index was not set before infix increment operation (in-place addition, $<var>++ ) while a regular assignment won't lead to notice .

To suppress Notice :

...
@$frequency[$val]++;

To avoid Notice :

...
$frequency[$val] = (isset($frequency[$val]))? $frequency[$val]+1 : 1;

The good practice is to avoid notices, warnings, errors ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM