foreach inside the for loop; keep looping

1.2k views Asked by At

I'm practicing on foreach and for loop at the moment and combining them leads me to unexpected result. Below is a foreach statement inside the for loop statement.

PHP:

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

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

OUTPUT:

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

EXPECTED OUTPUT:

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

Kindly tell me what I'm doing wrong and what is the solution for this.

PS: I don't want to used array keys and values. :)

3

There are 3 answers

7
Marc B On BEST ANSWER

You want foreach only:

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

You don't need to nest loop styles just to get the array keys - PHP can trivially give them to you with the as $key => $value version of foreach.

0
Jon On

foreach loops through the entire array every pass through the outer loop. Try this:

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

You can use While loop

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

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

result:

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