Page 1 of 1

how to use foreach

Posted: Sun Apr 12, 2009 9:15 am
by srichandar
hi all,

how this statement "for($i=1; $i<=10; $i++)" can be written using foreach loop


thanks in advance,
sridhar

Re: how to use foreach

Posted: Sun Apr 12, 2009 9:23 am
by dethron

Code: Select all

<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with the last element
?>
To find this example
1.) Go to http://www.php.net
2.) Search for "foreach"
3.) Then you got it.

P.S: Newbies are a little lazy i guess :)) Nice to be back here again ;)

Re: how to use foreach

Posted: Sun Apr 12, 2009 1:23 pm
by php_east
srichandar wrote:how this statement "for($i=1; $i<=10; $i++)" can be written using foreach loop
foreach is for array. is you wish to rewrite you need $i as an array. so there is no equivalent.

Re: how to use foreach

Posted: Sun Apr 12, 2009 6:16 pm
by dethron
php_east wrote:foreach is for array. is you wish to rewrite you need $i as an array. so there is no equivalent.
then put all these numbers into an array. i am not saying it is the logical way, but if you look at the example i gave you will see that you can use it like the way he asked.

Re: how to use foreach

Posted: Sun Apr 12, 2009 7:56 pm
by php_east
uh, never mind.

Re: how to use foreach

Posted: Tue Apr 14, 2009 12:44 pm
by McInfo

Code: Select all

for  ($i = 1; $i <= 10; $i++)
is equivalent to

Code: Select all

foreach (range(1, 10) as $i)
But the first is more efficient.

Edit: This post was recovered from search engine cache.

Re: how to use foreach

Posted: Tue Apr 14, 2009 8:02 pm
by socket1
I believe you want to use while for that.

while ($i=1; $i<=10; $i++) {
}

Re

Posted: Tue Apr 14, 2009 8:11 pm
by McInfo
socket1 wrote:I believe you want to use while for that.

while ($i=1; $i<=10; $i++) {
}
Did you test your code before you posted it?

http://php.net/while

Edit: This post was recovered from search engine cache.

Re: how to use foreach

Posted: Tue Apr 14, 2009 8:18 pm
by socket1
Alright it doesn't work I was suspecting that but if if you want code that works this is where i've used such a statement:

Code: Select all

$i = 500;
while ($i>1 && $i<100) {
    $i = mt_rand(0, 101);
}
It only stops if mt_rand generates a 0 or a 101.

Re: how to use foreach

Posted: Tue Apr 14, 2009 8:23 pm
by php_east
McInfo wrote:

Code: Select all

for ($i = 1; $i <= 10; $i++)
is equivalent to

Code: Select all

foreach (range(1, 10) as $i)
But the first is more efficient.
ah, so there is an equivalent apparently. one learns something new every day. thanks.

Re

Posted: Tue Apr 14, 2009 8:26 pm
by McInfo
The while loop that is equivalent to

Code: Select all

for ($i = 1; $i <= 10; $i++)
is

Code: Select all

$i = 1;
while ($i <= 10) {
    $i++;
}
Edit: This post was recovered from search engine cache.