Undefined offset error, but offset is not undefine

2019-05-08 04:12发布

问题:

I'm getting:

Notice: Undefined offset: 0 

in my code, however I can print_r the element I am trying to get and its clearly defined.

function get_members($entries_found) {
   $members = $entries_found[0]['member'];
   ...
}

If I print_r($members) I get the expected output, however I'm still getting the Notice.

Any clues?

回答1:

Do

var_dump($entries_found);

To check that the array does indeed have an offset of zero. Other things you can try would be reseting the array pointer

reset($entries_found);

of checking if it's set first

if (isset($entries_found[0]['member'])) // do things

If all else fails you could just supress the notice with

$members = @$entries_found[0]['member'];


回答2:

I don't really know what happens with your $entries_found before accessing it from get_members

But i had the same problem. print_r and var_dump showed me, that the index exists but when i tried to access it i got the offset error

In my case i decoded a json string with json_decode without setting the assoc flag.

// Not working
$assocArray = json_decode('{"207":"sdf","210":"sdf"}');
echo $assocArray[207];


// working witht the assoc flag set
$assocArray = json_decode('{"207":"sdf","210":"sdf"}', true);
echo $assocArray[207];

Got my solution from here: Undefined offset while accessing array element which exists