即使匹配的值存在,为什么我在数组中搜索的值也不会返回true?

时间:2019-01-29 10:53:33

标签: php arrays oop if-statement foreach

最近3个小时,我一直在努力解决这个问题。 我生成一个随机数,0-36。 我还生成了一个以2为步长的数字0-36的数组(仅不偶数)。 我在随机数和数组上都执行了var_dump,并且可以在数组中看到匹配的值,但是,我的if语句不会返回true。

我也尝试了in_array,但没有成功。我尝试了array_map,没有运气...我无休止地在Google上搜索并尝试了所有我能想到的东西。有什么作用?

$this->number = rand(0, 36); 
$this->colorBlack = array(range(1, 36, 2));

foreach ($this->colorBlack as $this->color){

            var_dump($this->color);
            var_dump($this->number);

        if ($this->color == $this->number){
            echo 'yes';
            var_dump($this->colorBlack);
        }
    }

当生成的随机数与数组中的值匹配时,我希望上面的代码为return true,但是事实并非如此。

Var转储如下:

array(18) { [0]=> int(1) [1]=> int(3) [2]=> int(5) [3]=> int(7) [4]=> int(9) [5]=> int(11) [6]=> int(13) [7]=> int(15) [8]=> int(17) [9]=> int(19) [10]=> int(21) [11]=> int(23) [12]=> int(25) [13]=> int(27) [14]=> int(29) [15]=> int(31) [16]=> int(33) [17]=> int(35) } int(26)

2 个答案:

答案 0 :(得分:1)

函数range已经返回一个数组,并且您在此行中再次将其包装在数组中:

$this->colorBlack = array(range(1, 36, 2));

这意味着现在您有了一个包含1个项目的数组,这是范围返回的数组。

运行foreach ($this->colorBlack as $this->color){时,此部分$this->color将指向第一项,即数组。

然后,这行if ($this->color == $this->number){将范围内的数字与无法正常工作的数组进行比较。

一种解决方案可能是不将范围的返回值包装在像这样的数组中:

$this->colorBlack = range(1, 36, 2);

Demo php

答案 1 :(得分:0)

您是一个较短的foreach循环,您的值是嵌套的,所以往下走一层,即:

<?php
$number = rand(0, 36);
$colorBlack = array(range(1, 36, 2));

foreach ($colorBlack as $color){
   foreach($color as $k => $gotcha) {
       if ($gotcha == $number){
           echo 'yes';
           var_dump($colorBlack);
       }
   }
}