RE: [PHP] Foreach question
| From: | Dajka Tamás | Date: | Tue, 05 Jul 2011 14:20:35 +0000 |
| Subject: | RE: [PHP] Foreach question | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-313876@lists.php.net to get a copy of this message | ||
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@interjinn.com]
Sent: Tuesday, July 05, 2011 4:06 PM
To: Dajka Tamas
Cc: php-general@lists.php.net
Subject: Re: [PHP] 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.