php array returns undefined but print_r shows otherwise

805 Views Asked by At
foreach($jsonmediationinfo as $value1) {
    echo $value1['mstatus'];
    print_r($jsonmediationinfo);
}

Output:

1Array ( [0] => Array ( [mstatus] => 1 [mhearingnum] => first [mminutes] => adakjaflafjlarjkelfkalfkd;la ) [1] => Array ( [mhearingnum] => second [mminutes] => ) [2] => Array ( [mhearingnum] => third [mminutes] => ) ) 

Undefined index: mstatus in ... on line 265 line 265 is line echo $value1['mstatus'];

This is my php server side code.This used to saved data into database but i am getting undefined index:mstatus in line 265. But in the print_r the index mstatus clearly exists. Also if I check in database when I update the data the values changes to correct value. In this example the value is changed to 1.

What is the problem in this line of code. Any suggestion is appreciated

2

There are 2 best solutions below

0
On BEST ANSWER

The array you're looping looks like this:

Array (
    [0] => Array (
        [mstatus] => 1
        [mhearingnum] => first
        [mminutes] => adakjaflafjlarjkelfkalfkd;la
    )
    [1] => Array (
        [mhearingnum] => second
        [mminutes] =>
    )
    [2] => Array (
        [mhearingnum] => third
        [mminutes] =>
    )
)

Only the sub array at the first index contains mstatus, so on the second iteration of the loop it throws the exception. It's best to check if mstatus is present using isset($value1['mstatus']).

foreach ($jsonmediationinfo as $value1) {
    if (isset($value1['mstatus'])) {
        echo $value1['mstatus'];
        print_r($jsonmediationinfo);
    }
}

In a real life scenario you could handle your status like this:

foreach ($jsonmediationinfo as $value1) {
    if (isset($value1['mstatus']) && ($value1['mstatus'] === 1 || $value1['mstatus'] === true)) {
        // Do something with the positive status
    } else {
        // Do something with the negative/missing status
    }
}
0
On

As RuubW mentioned

you could handle real life condition like this also

    foreach ($jsonmediationinfo as $value1) {
        if (array_key_exists('mstatus',$value1)) {
            echo $value1['mstatus'];
        } 
        print_r($jsonmediationinfo);
    }