简体   繁体   中英

foreach inside the for loop; keep looping

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. :)

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

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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