比较开关内的数字的奇怪问题

时间:2015-07-10 06:46:16

标签: php if-statement switch-statement

我正在尝试使用switch case这样的类别ID生成css类名。

我在切换机箱中有多个条件,但我们只会将此视为创建奇怪的输出。

示例代码:

<?php
$value = '907';//base value

$value_array =  str_split($value);//create array of string, if its int.

var_dump($value_array);//debug whats in array

switch($value_array[0]){

case 9:

$final = 'i came inside 9';

if($value_array[1].$value_array[2] == 07){
//check whther last 2 digits are 07
    $final = 'i came inside 907';
}else if($value_array[1].$value_array[2] == 09){
//chcek whether last 2 digits are 09
    $final = 'i came inside 909';
}
break;
}

echo $final;

上面的代码将输出显示为[$value is 907]

array(3) {
  [0]=>
  string(1) "9"
  [1]=>
  string(1) "0"
  [2]=>
  string(1) "7"
}
i came inside 907

哪种行为正确。但是,如果我将基值从907更改为909,则输出为[$value is 909]

array(3) {
  [0]=>
  string(1) "9"
  [1]=>
  string(1) "0"
  [2]=>
  string(1) "9"
}
i came inside 9

输出应为i came inside 909

  • 为什么?

  • 为什么它适用于907而不适用于909,即使它们都具有相同的数据类型?

  • 我知道它们是字符串,我应该将字符串与字符串进行比较,但为什么它只使用一个例子而不是另一个例子?

4 个答案:

答案 0 :(得分:4)

0709octal numbers,其中09是一个无效的八进制数,因此它最终会为0.这就是为什么你的代码没有& #39;按你的意愿工作。

要解决它,只需将其放在引号中,例如

if($value_array[1].$value_array[2] === "07"){
//check whther last 2 digits are 07
    $final = 'i came inside 907';
}else if($value_array[1].$value_array[2] === "09"){
//chcek whether last 2 digits are 09
    $final = 'i came inside 909';
}

答案 1 :(得分:2)

您将数组值与格式为八进制数的整数进行比较(请参阅http://php.net/manual/de/language.types.integer.php)。

07是一个有效的八进制数,代表值7,您的比较有效。

另一方面,

09是一个无效的八进制数。因此,比较不起作用。

为了解决您的问题,您需要将'围绕值放置,以便将它们解释为字符串。

if($value_array[1].$value_array[2] == '07'){
//check whther last 2 digits are 07
    $final = 'i came inside 907';
}else if($value_array[1].$value_array[2] == '09'){
//chcek whether last 2 digits are 09
    $final = 'i came inside 909';
}

答案 2 :(得分:0)

当您使用07时,PHP interprets it as an octal number。它知道09不是八进制,因为9在Octal系统中无效。

尝试79,或'07''09'

<?php
$value = '907'; //base value

$value_array =  str_split($value); //create array of string, if its int.

var_dump($value_array); //debug whats in array

switch ($value_array[0])
{
    case 9:
        $final = 'i came inside 9';

        if ($value_array[1].$value_array[2] == '07')
        {
            //check whther last 2 digits are 07
            $final = 'i came inside 907';
        }
        elseif($value_array[1].$value_array[2] == '09')
        {
            //chcek whether last 2 digits are 09
            $final = 'i came inside 909';
        }

        break;
}

echo $final;

答案 3 :(得分:0)

因为在php 09中会将其视为八进制数并将其转换为0,其中07始终为07

当您尝试echo 09时,它会输出007 07

所以不要松散地比较==,而是需要使用严格比较===,即

if($value_array[1].$value_array[2] === "07"){
//check whther last 2 digits are 07
    $final = 'i came inside 907';
}else if($value_array[1].$value_array[2] === "09"){
//chcek whether last 2 digits are 09
    $final = 'i came inside 909';
}