简体   繁体   中英

PHP Undefined index - Isset() is false when index is in array

I'm not able to figure out what the issue is here. I have an associative array with predefined indexes and when trying to access one of the indexes, I'm getting the undefined index error, here's the code,

        if(!isset($score_value[$index])){
            echo $index . ' isnt in array: <br/>';
            print_r($score_value);
            exit;
        }
        print_r($score_value[$index]);

The output was this:

pi_cholesterol isn't in array:

Array ( 
    [pi_overall_health] => Array ( 
        [4] => 4 [1] => 1 [2] => 4 [3] => 1 
    ) 
    [pi_bmi] => Array ( 
        [Healthy Weight] => 4 [Obese] => 3 [Overweight] => 3 
    ) 
    [pi_cholesterol] => Array ( 
        [Yes - its level is too high] => 6 [Yes - its level is ok] => 3 [No] => 1 
    ) 
)

As you can see pi_cholesterol is an index in the array but for some reason isset() is flagging it as not being in the array, same thing happens if I try with array_key_exists() . There might be some simple thing I'm overlooking but I can't see it.

Any suggestions welcome!

Sorry my own stupid mistake, $index was being overwritten in another place in the code and was being appended with a trailing whitespace.

Mjh, axiac and rahul_m suggesting to use trim() helped me solve this.

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