duandeng7132 2015-01-07 19:38
浏览 80
已采纳

isset()从作为具有任何键的数组访问的字符串变量返回true

I face a problem like this:

$area="Dhaka";

isset($area); //returns true which is OK

isset($area['division']); //returns true why?

// actually, any array key of area returns true

isset($area['ANY_KEY']);//this is my question 1

isset($area['division']['zilla');//now it returns false. 

//as I know it should returns false but why previous one was true.

Now if I do this:

$area['division'] = "Dhaka";
isset($area); // returns true which is OK
isset($area['division']); // returns true it's also OK
isset($area['ANY_KEY']); // returns false. I also expect this

isset($area['division']['ANY_KEY']); // returns true why? question #2

Basically both of my questions are the same.

Can anyone explain this?

  • 写回答

6条回答 默认 最新

  • doudundian9558 2015-01-07 19:42
    关注

    As with every programming language in existence, a string is stored as an array of characters.

    If I did:

    $area = "Dhaka";
    echo $area[0];
    

    It would return D.

    I could also echo the whole string by doing:

    echo $area[0].$area[1].$area[2].$area[3].$area[4];
    

    PHP will also type juggle a string into 0 when passed in a manner that accepts only integers.

    So by doing:

    echo $area['division'];
    

    You would essentially be doing:

    echo $area[0];
    

    and again, getting D.

    That's why isset($area['division']) returns a true value.

    Why doesn't $area['foo']['bar'] (aka $area[0][0]) work? Because $area is only a single-dimension array.

    The best approach to handle this problem when you're working with a variable that could either be a string or an array is to test with is_array() before trying to treat your variable as an array:

    is_array($area) && isset($area['division'])
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制