【问题标题】:Why won't the value I am searching in an Array return true even though the matching value exists?为什么即使匹配值存在,我在数组中搜索的值也不会返回 true?
【发布时间】:2019-01-29 10:53:33
【问题描述】:

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

我也试过in_array,但没有奏效。我试过array_map,没有运气......我无休止地用谷歌搜索并尝试了我能想到的一切。什么给了?

$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)

【问题讨论】:

  • 例如,您的 var 转储会产生什么?
  • 没有一个 return 声明,那么您究竟希望在这里“返回 true”什么呢?
  • 'Yes' 没有被回显——我不应该说“return true”。
  • $this->color 是一个数组,$this->number 是一个标量整数。将它们与 == 进行比较并期望在这里相等是没有意义的。
  • secure.php.net/manual/en/function.range.php range() 已经创建了一个数组

标签: php arrays oop if-statement foreach


【解决方案1】:

函数range 已经返回了一个数组,你在这一行再次将它包装在一个数组中:

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

这意味着现在你有一个包含 1 项的数组,也就是 range 返回的数组。

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

那么if ($this->color == $this->number){这一行正在将范围内的数字与一个不起作用的数组进行比较。

一种解决方案可能是不将 range 中的返回值包装在一个数组中,例如:

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

Demo php

【讨论】:

  • 一个精彩的解释。非常感谢您花时间帮助我。非常感谢!
【解决方案2】:

你的 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);
       }
   }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-25
    • 1970-01-01
    • 1970-01-01
    • 2019-12-04
    • 1970-01-01
    • 2019-04-03
    • 1970-01-01
    • 2017-07-25
    相关资源
    最近更新 更多