字符串和0的比较返回意外结果

时间:2017-04-02 23:35:58

标签: php

我开始学习PHP并遇到以下问题:

function dechex_helper($dec){
    $hex = dechex($dec);
    if($hex == 0){
        return '00';
    }
    return $hex;
}

function webColors($red, $green, $blue){
    return '#'.dechex_helper($red).dechex_helper($green).dechex_helper($blue);
}

echo 'webColors(255, 0, 0)'.': '.webColors(255, 0, 0).'<br>';
echo 'webColors(0, 0, 255)'.': '.webColors(0, 0, 255).'<br>';
echo 'webColors(255, 0, 191)'.': '.webColors(255, 0, 191).'<br>';
echo 'webColors(0, 0, 0)'.': '.webColors(0, 0, 0).'<br>';

结果:

webColors(255, 0, 0): #000000
webColors(0, 0, 255): #000000
webColors(255, 0, 191): #000000
webColors(0, 0, 0): #000000

但如果我更改了这一行:

if($hex == 0){

要:

if($hex === '0'){

结果是正确的:

webColors(255, 0, 0): #ff0000
webColors(0, 0, 255): #0000ff
webColors(255, 0, 191): #ff00bf
webColors(0, 0, 0): #000000

有人可以解释一下它会发生什么吗?

0 个答案:

没有答案