2015-07-10 60 views
2

我想从类别ID使用switch case像这样生成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

0709octal numbers,其中09是无效的八进制数,所以它最终会为0。这就是为什么你要到您的代码不起作用。

要解决它只是把它放在引号,例如,

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'; 
} 
0

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

尝试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; 
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'; 
} 
0

因为在PHP中09会认为它是八进制数,并将其转换成0其中作为07它总是07

当您尝试echo 09它会输出你00707

因此,不需要比较松散地==您需要使用严格比较===

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'; 
}