RE: Foreach question

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

 



Tried, gives the same result with one element :(

What's working:

$cats = array( array( 'id' => 1 ) );
while ( $c = array_shift($cats) ) {
	echo $c['id'];
	if ( $c['id'] < 5 ) {
		$c['id']++;
		$cats[] = $c;
	}
}

But this is 'while' and it pops all elements from the array...

Cheers,

	Tamas



-----Original Message-----
From: Louis Huppenbauer [mailto:louis.huppenbauer@xxxxxxxxx] 
Sent: Tuesday, July 05, 2011 4:12 PM
To: Robert Cummings
Cc: Dajka Tamas; php-general@xxxxxxxxxxxxx
Subject: Re:  Foreach question

Or maybe he tried to do the following?

<?php
foreach ( $cats as&$c ) {
               echo $c['id'];
               if ($c['id']<  5) {
                              $cats[] = array('id' => ($c['id'] + 1));
               }
}
?>

2011/7/5 Robert Cummings <robert@xxxxxxxxxxxxx>:
>
> 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
>
>

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



-- 
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