【问题标题】:PHP output number with leading zeros incorrectly带前导零的 PHP 输出数字错误
【发布时间】:2013-12-13 21:17:20
【问题描述】:

我在这样的文件中有一行:

0000000/BirthstoneEnsemble/f/0/1380152724

我被$pieces = explode("/", $line);炸了

当我执行 echo $pieces[0] == "0000000" 时,它返回 false。我尝试将pieces[0] 转换为字符串,但总是不正确。

function build_file_assoc() {
global $dir;
$assoc = [];

   $file_assoc = file($dir . 'rsnjxdlxwxwun.dbt'); 

   for($i = 0; $i < count($file_assoc) - 1; $i++) {

   if($i > 0) {

        list($parent_folder, $image_name, $tag, $size, $date) = explode("/", $file_assoc[$i]);
        $assoc[] = [
            'parent_folder' => (string)$parent_folder,
            'image_name' => $image_name,
            'tag' => $tag,
            'size' => $size,
            'date' => $date
        ];

       }
   }

   return $assoc;
}

$g = build_file_assoc();

$first = $g[0]['parent_folder'];

echo $first == "0000000"; // false

文件内容:

0000000/BirthstoneEnsemble/f/0/1380152724
0000000/Thumbs.db/a/83968/1384248954
0000000/bridal images for frame/f/0/1380152879

【问题讨论】:

  • 你确定$pieces[0]是你认为的那样吗?
  • 是的。这令人沮丧,因为它在视觉上打印为 0000000,这是我所期望的。在引擎盖下,显然不是这样。
  • 您是否尝试过使用严格比较===
  • 用完整代码更新了问题。是的,我尝试过 ==、===、将两边都转换为字符串等。
  • 哦,隐藏的空间让人头疼。

标签: php integer


【解决方案1】:

尝试打印数组 print_r($pieces),你会看到 exlode 后特定字段中保存的内容。

【讨论】:

    【解决方案2】:

    如果我从您的问题中运行代码,它会起作用:

    <?php 
    $line = '0000000/BirthstoneEnsemble/f/0/1380152724';
    $pieces = explode("/", $line);
    
    echo var_dump($pieces[0] == "0000000"); //true
     ?>
    

    【讨论】:

    • 文件中的行没有用引号引起来..您的示例使整个内容成为字符串
    • @StephenKnoth 是的,但我在您发布完整源代码之前 写了它。尽管如此,file() 可能会返回一个字符串数组。您可以使用var_dump($first); 进行测试
    【解决方案3】:

    我会使用相同的比较运算符并键入 cast pieces[0] 作为字符串。

    $line = '0000000/BirthstoneEnsemble/f/0/1380152724';
    
    $pieces = explode('/',$line);
    
    //echo '<pre>',print_r($pieces),'</pre>';
    
    if((string)$pieces[0]==='0000000'){
        echo true;
    }else{
        echo false;
    }
    // output: 1
    

    【讨论】:

      【解决方案4】:

      var_dump

      检查您的 piece 的实际值,因为其中可能有空格或制表符 - var_dump 会为您显示。

      类似问题

      看看这个post

      【讨论】:

        猜你喜欢
        • 2022-12-13
        • 1970-01-01
        • 1970-01-01
        • 2011-03-01
        • 1970-01-01
        • 2010-09-13
        • 2010-12-25
        相关资源
        最近更新 更多