how to use foreach
Moderator: General Moderators
-
srichandar
- Forum Newbie
- Posts: 6
- Joined: Thu Apr 02, 2009 9:36 am
how to use foreach
hi all,
how this statement "for($i=1; $i<=10; $i++)" can be written using foreach loop
thanks in advance,
sridhar
how this statement "for($i=1; $i<=10; $i++)" can be written using foreach loop
thanks in advance,
sridhar
Re: how to use foreach
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
?>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
Re: how to use foreach
foreach is for array. is you wish to rewrite you need $i as an array. so there is no equivalent.srichandar wrote:how this statement "for($i=1; $i<=10; $i++)" can be written using foreach loop
Re: how to use foreach
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.php_east wrote: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
uh, never mind.
Re: how to use foreach
Code: Select all
for ($i = 1; $i <= 10; $i++)Code: Select all
foreach (range(1, 10) as $i)Edit: This post was recovered from search engine cache.
Last edited by McInfo on Mon Jun 14, 2010 1:42 pm, edited 1 time in total.
Re: how to use foreach
I believe you want to use while for that.
while ($i=1; $i<=10; $i++) {
}
while ($i=1; $i<=10; $i++) {
}
Re
Did you test your code before you posted it?socket1 wrote:I believe you want to use while for that.
while ($i=1; $i<=10; $i++) {
}
http://php.net/while
Edit: This post was recovered from search engine cache.
Last edited by McInfo on Mon Jun 14, 2010 1:43 pm, edited 1 time in total.
Re: how to use foreach
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:
It only stops if mt_rand generates a 0 or a 101.
Code: Select all
$i = 500;
while ($i>1 && $i<100) {
$i = mt_rand(0, 101);
}Re: how to use foreach
ah, so there is an equivalent apparently. one learns something new every day. thanks.McInfo wrote:is equivalent toCode: Select all
for ($i = 1; $i <= 10; $i++)But the first is more efficient.Code: Select all
foreach (range(1, 10) as $i)
Re
The while loop that is equivalent to
is
Edit: This post was recovered from search engine cache.
Code: Select all
for ($i = 1; $i <= 10; $i++)Code: Select all
$i = 1;
while ($i <= 10) {
$i++;
}