【问题标题】:PHP: IF sentence is run, but dumps says it shouldn'tPHP:如果语句运行,但转储说它不应该
【发布时间】:2014-10-06 10:04:51
【问题描述】:

我坐在一个非常简单的图片上传器上,上传的第一张图片将以特殊方式处理。然后我对所有文件运行一个循环,并跳过第一张图片。

为此,我将第一个图像命名为 headImage,当它被移动时我会跳过它,并对其进行其他处理。

我已经删除了所有多余的代码,只显示导致我的问题的循环:

排序后的图像数组:

array (size=5)
    'headImage' => 
        array (size=5)
            'name' => string '8-skilling-1606-eller-07-54-1-h93a.jpg' (length=38)
            'type' => string 'image/jpeg' (length=10)
            'tmp_name' => string '/tmp/phpNUoAtX' (length=14)
            'error' => int 0
            'size' => int 37748
    0 => 
        array (size=5)
            'name' => string '807003718_2_Big.jpg' (length=19)
            'type' => string 'image/jpeg' (length=10)
            'tmp_name' => string '/tmp/php1TXBdm' (length=14)
            'error' => int 0
            'size' => int 36328

如果fileKey是“headImage”则跳过Foreach循环,并转储fileKey

foreach($uploadFiles as $fileKey => $file){
    if($fileKey == "headImage"){
        var_dump($fileKey);
        continue;
    }
}

以及 var_dump 的输出:

string 'headImage' (length=9)
int 0

现在,当 $fileKey 的值明显不是“headImage”时,为什么运行 if 语句?

【问题讨论】:

    标签: php if-statement continue var-dump


    【解决方案1】:

    比较两个字符串的最佳和安全方法是使用 php strcmp 函数

    这样使用:

    foreach($uploadFiles as $fileKey => $file){
        if(strcmp($fileKey ,"headImage") == 0){
            var_dump($fileKey);
            continue;
        }
    }
    

    PHP strcmp function Document

    【讨论】:

      【解决方案2】:

      因为"string" == 0 在 PHP 中。

      你也得用类型比较,试试===比较:

      foreach($uploadFiles as $fileKey => $file){
          if($fileKey === "headImage"){
              var_dump($fileKey);
              continue;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-01-16
        • 2013-05-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多