简体   繁体   English

如何将此for循环转换为while循环?

[英]How can I convert this for loop into a while loop?

I'm trying to adapt this for loop: 我正在尝试将其用于循环:

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

to this one: 对此:

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

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

But i can't find the way to make it works. 但是我找不到使它工作的方法。 It gives me an empty page. 它给了我一个空白页。 Thanks in advance. 提前致谢。

$resultado = false;
while($value = array_shift($nombresArreglo)) {
    if ($nombre === $value) {
        $resultado = true;
        break;
    }
}

note: the array $nombresArreglo will be empty after this loop is executed, will only work if you don't need this array anymore 注意:执行此循环后,数组$nombresArreglo将为空,仅在不再需要此数组时才起作用

Just use the simple control structure, initialize first, then while is the condition, and dont forget to increment. 只需使用简单的控制结构,先进行初始化,然后再进行条件设置,别忘了增加。 You forget initialization and the increment. 您会忘记初始化和增量。 An example: 一个例子:

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

Output will be like: Bill Gates found! at index 2 输出将类似于: Bill Gates found! at index 2 Bill Gates found! at index 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM