Question

<?php
$x=0;
foreach($a as $b) {
    $x++;
    echo $x; // output 1 2 3 4 
    echo $b; // output a b c d
}
?>
<div>SOME HTML ELEMENTs</div>
<?PHP
foreach($c as $d) {
    $y=0;
    $y++;
    echo $y; // output 1 1 1 1 (should be 1 2 3 4!!!!);
    echo $d; // output e f g h
}
?>

Why $y will not increment? but i can tell that the loop is working since i get the correct $d value to output. can someone explain why this might be? I am burning my brain out.

Was it helpful?

Solution

On every iteration, you are resetting $y=0;, causing it to always have the value of 1 at the echo. So move that out of the loop:

$y=0;
foreach($c as $d) {
    ...
}

OTHER TIPS

<?php
$x=0;
foreach($a as $b) {        
    $x++;
    echo $x;
    echo $b; 
}
?>
<div>SOME HTML ELEMENTs</div>
<?PHP
$y=0;
foreach($c as $d) {
    $y++;
    echo $y; 
    echo $d;
}
?>

You are reseting $x & $y to 0 with each loop iteration.

foreach($a as $b) {
    $x=0;
    $x++;
    …

foreach($c as $d) {
    $y=0;
    $y++;
    …

Change it to this:

$x=0;
foreach($a as $b) {
    $x++;
    …

$y=0;
foreach($c as $d) {
    $y++;
    …
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top