Use Array in a While Loop PHP

Asked By 70 points N/A Posted on -
qa-featured

 

Hello guys, please help me, I am confused about how to use array in a while loop, can you give me examples? Thanks

SHARE
Answered By 5 points N/A #104387

Use Array in a While Loop PHP

qa-featured

Hi Rhon,

Take a look at this code below. This is a very sample PHP code for using array in while loops.

<?php
    $number = array(1,2,3,4,5);
    $i = 5;
    while($i >= 0)
    {
        echo 'number['.$i.'] ='.$number[$i].'<br />';
        $i–;
    }
   

This is an example on how to access associative array using while loop.


    $losers['me'] = 1;
    $losers['you'] = 2;
    $losers['they'] = 3;
    echo 'losers<br />';
    while( $element = each( $losers ) )
    {
    echo $element[ 'key' ];
    echo ' – ';
    echo $element[ 'value' ];
    echo '<br />';
    }

// the other way around


    $winners[1] = 'me';
    $winners[2] = 'you';
    $winners[3] = 'they';
    echo 'winners<br />';
    while( $element = each( $winners ) )
    {
    echo $element[ 'key' ];
    echo ' – ';
    echo $element[ 'value' ];
    echo '<br />';
    }
?>

Related Questions