fore循环中的foreach;保持循环

时间:2015-06-08 21:23:58

标签: php for-loop foreach

我正在练习foreach和for循环,结合它们会让我意想不到的结果。下面是for循环语句中的foreach语句。

  

PHP:

<?php
$names = array("A", "B", "C", "D"); 

for ($i = 0; $i <= 3; $i++) 
{
    foreach ($names as $name) 
    {
        echo "$name = $i ";
    }
}
?>

输出:

A = 0 B = 0 C = 0 D = 0 A = 1 B = 1 C = 1 D = 1 A = 2 B = 2 C = 2 D = 2 A = 3 B = 3 C = 3 D = 3

预期输出

A = 0 B = 1 C= 2 D = 3

请告诉我我做错了什么,解决方法是什么。

PS:我不想使用数组键和值。 :)

3 个答案:

答案 0 :(得分:1)

每次遍历外部循环时,foreach遍历整个数组。试试这个:

$i = 0;
foreach ($names as $name) {
    echo "$name = $i ";
    $i++;
}

答案 1 :(得分:1)

您只需要foreach

foreach($names as $key => $value) {
   echo "$value: $key";
}

您不需要为了获取数组键而嵌套循环样式 - PHP可以使用as $key => $value版本的foreach轻松地为它们提供。

答案 2 :(得分:-1)

您可以使用While循环

$names = array("A", "B", "C", "D"); 
$i=0;

    foreach ($names as $name) 
    {
        echo "$name = $i ";
        $i++;
        array_pop($names);
    }

<强>结果:

  

A = 0 B = 1 C = 2 D = 3