【问题标题】:How can I convert this for loop into a while loop?如何将此 for 循环转换为 while 循环?
【发布时间】:2014-07-07 18:20:41
【问题描述】:

我正在尝试调整这个 for 循环:

    $nombresArreglo = ['John','Bruce Lee','Bill Gates','Pedro','Juan','Maria','James    Gosling','Andres'];

    $nombre = 'Bill Gates';

    $resultado = false;

    $i=2;

    for ($i = 0;$i < count($nombresArreglo); $i++){ 

        if ($nombresArreglo[$i] == $nombre){
        $resultado = true;
        break;
        }
    }

    if ($resultado == true){
        echo $nombre . ' found!';
    }
    else{
    echo $nombre. ' doesnt exists';
    }

到这个:

    while ($i < count($nombresArreglo)){

        if ($nombresArreglo[$i] == $nombre){
            $resultado = true;
            break;
        }    
        if ($resultado == true){
            echo $nombre . ' found';
        }
    }

但我找不到让它工作的方法。它给了我一个空白页。提前致谢。

【问题讨论】:

  • 您没有增加$i。将$i++ 放在循环结束之前。并检查 $resultado == true 是否在循环之外。
  • 另外,在进入while循环之前初始化$i

标签: php for-loop while-loop


【解决方案1】:

只要使用简单的控制结构,先初始化,再while为条件,别忘了递增。你忘记了初始化和增量。一个例子:

$nombresArreglo = ['John','Bruce Lee','Bill Gates','Pedro','Juan','Maria','James Gosling','Andres'];
$nombre = 'Bill Gates';
$resultado = false;
$i = 0; // <-- you forget initilize
while($i != sizeof($nombresArreglo)-1) { // <-- condition
    if($nombresArreglo[$i] == $nombre) {
        echo $nombre . ' found! at index ' . $i;
        $resultado = true;
    }
    $i++; // <-- you forget increment
}

输出将类似于:Bill Gates found! at index 2

【讨论】:

    【解决方案2】:
    $resultado = false;
    while($value = array_shift($nombresArreglo)) {
        if ($nombre === $value) {
            $resultado = true;
            break;
        }
    }
    

    注意:循环执行后数组$nombresArreglo将为空,只有当你不再需要这个数组时才会起作用

    【讨论】:

    • 我完全同意删除评论的那个人。 :D
    • 我很想对此投反对票,因为 OP 没有要求更改原始数组。
    • 这只是关于 OP 要求的主题,但更多的是不是主题。 -1
    猜你喜欢
    • 2021-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-01
    • 1970-01-01
    • 2023-01-22
    • 2018-03-19
    • 2017-02-14
    相关资源
    最近更新 更多