Php 如何将此for循环转换为while循环?
我正在尝试将此应用于循环:Php 如何将此for循环转换为while循环?,php,for-loop,while-loop,Php,For Loop,While 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++){
$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';
}
}
但我找不到办法让它工作。它给了我一页空白。提前谢谢
$resultado = false;
while($value = array_shift($nombresArreglo)) {
if ($nombre === $value) {
$resultado = true;
break;
}
}
注意:执行此循环后,$nombresArreglo数组将为空,仅当您不再需要此数组时才起作用只需使用简单的控制结构,先初始化,然后是条件,不要忘记递增。您忘记了初始化和增量。例如:
$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
}
输出将是这样的:比尔·盖茨找到了!在索引2中,您没有增加$i。将$i++放在循环结束之前。检查循环外的$resultado==true。另外,在进入while循环之前初始化$i。我完全同意删除注释的人的观点:我很想否决这一点,因为OP没有要求更改原始数组。这与OP要求的主题略有关系,但更多内容与主题无关-1.