RE: Foreach question

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

 



Hi,

Yeah, I'm really want to do that, since I'm working with the elements of the original array ( skipped that part in sample code ).

I've tried your suggestion, but it gives the same result, so on just one input is just gives back '1'.

What troubles me, that foreach gives an inconsistent working. Why is 'foreach' checking element count at all and working differently with different element counts? That's not normal is my opinion. 'foreach' shouldn't do this:

if ( count($elements) == 1 ) then loop 1;
else loop normally;

and that's what is does now, since when it's more than one element it's working like a while loop, with checking the condition before ( and after ) every run. ( if 'foreach' would check that the current run is the last one before executing the current loop, the results would be the same with each case )

Cheers,

	Tamas

-----Original Message-----
From: Robert Cummings [mailto:robert@xxxxxxxxxxxxx] 
Sent: Tuesday, July 05, 2011 4:06 PM
To: Dajka Tamas
Cc: php-general@xxxxxxxxxxxxx
Subject: Re:  Foreach question


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