Re: Foreach question

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 




On 11-07-05 09:40 AM, Dajka Tamas wrote:
Hi all,



I've bumped into an interesting thing with foreach. I really don't know, if
this is normal working, or why it is, so I got curious.



The script:



foreach ( $cats as&$c ) {

                echo $c['id'];

                if ( $c['id']<  5 ) {

                               $c['id']++;

                               $cats[] = $c;

                }

}

That's a bizarre loop... you're feeding references to elements of the array back into the array over which the loop is iterating. If you REALLY want to do what you are doing, then do the following:

<?php

foreach( array_keys( $cats ) as $key )
{
    $c = &$cats[$key];

    echo $c['id'];

    if( $c['id'] < 5 )
    {
        $c['id']++;
        $cats[] = $c;
    }
}

?>

Cheers,
Rob.
--
E-Mail Disclaimer: Information contained in this message and any
attached documents is considered confidential and legally protected.
This message is intended solely for the addressee(s). Disclosure,
copying, and distribution are prohibited unless authorized.

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux