Undefined offset error, but offset is not undefined

不打扰是莪最后的温柔 提交于 2019-12-07 11:14:10

问题


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



来源:https://stackoverflow.com/questions/3209386/undefined-offset-error-but-offset-is-not-undefined

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!