drze7794 2016-12-12 16:16
浏览 20
已采纳

PHP - 奇怪的IF语句

Today I found a strange if statement that reports true without errors in PHP7. See the example below;

<?php
$array = array();

// This is true
if (!is_array($array)['key']) { echo 'test1'; }

// Strangely, this reports false
if (true['key']) { echo 'test2'; }

// This also reports true
if (!(1)['key']) { echo 'test3'; }

// Knowing the statement must be false (!(1)), you would think that false works; it doesn't
if (false['key']) { echo 'test4'; }

Can someone explain why it reports test1 and test3 as true when it is clearly faulty code without throwing errors? It did on PHP 5.6 for all statements except the first one (test1).

  • 写回答

1条回答 默认 最新

  • doucong8553 2016-12-12 16:27
    关注

    Answer is

    var_dump(is_array($array)['key'], true['key'], (1)['key'], false['key']);
    

    And it is

    NULL, NULL, NULL, NULL
    

    And a man string:

    For any of the types integer, float, string, boolean and resource, converting a value to an array results in an array with a single element with index zero and the value of the scalar which was converted. In other words, (array)$scalarValue is exactly the same as array($scalarValue).

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

报告相同问题?

悬赏问题

  • ¥15 livecharts wpf piechart 属性
  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置