doujiao2443 2016-08-28 12:02
浏览 62
已采纳

PHP - isset对非现有数组键返回true

I thought I knew everything about php until I bumped into this:

$foo = 'hello';
isset($foo['a']);     // returns false - OK
isset($foo['a']['b']; // returns false - OK
isset($foo['a'][0]);  // returns true! WTF?!

Could anybody explain me the result of the 4th line? Tested with php 5.5.36.

  • 写回答

1条回答 默认 最新

  • duanchandun1860 2016-08-28 12:06
    关注

    Well, the question is somewhat misleading, because isset returns true for any variable that is not null. Since $foo is a string, and not an array, $foo["a"] gives an Illegal string offset warning. PHP assumes that you meant to cast "a" as an integer offset and does that implicitly, turning $foo["a"] into $foo[0] which gives you the string "h" (the first offset of the string). Since the return value is another string the expression becomes "h"[0], which is just "h" again.

    So in other words, $foo["a"][0] where $foo = "hello" is the same thing as $foo[0][0] which gives us "h".

    But as far as non-existing array keys, isset would definitely return false since a non-existing key leads to a non-existing value which is implicitly null.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效