Page 1 of 2

How do i change a Foreach loop into a For loop?

Posted: Fri Jun 30, 2006 12:52 pm
by MrPotatoes
i have this code here:

Code: Select all

$thing = array	(
			(
				NUM1 => '1',
				NUM2 => '2',
				NUM3 => '3',
				NUM4 => '4',
				NUM5 => '5',
			)
		);

foreach ($thing as $key => $val)
{
	echo '\$thing index 1 = ' . $thing[$key] . '<BR>';
}
if this is an array in an array as it looks i'm not sure how to get to it by doubling up on for loops because there would only be one index but i tried that and it printed "Array" to the screen. basically debug garbage to me

i would like to turn that into a for loop because i find for loops easier and i like to keep my code as generic as possible for easy portablility for later. hey, you never know, ya know? lol

k, thx

Posted: Fri Jun 30, 2006 12:55 pm
by Robert Plank
Foreachs are more generic than fors

Even simpler:

Code: Select all

foreach ($thing as $key => $val)
{
        echo '\$thing index 1 = ' . $val . '<BR>';
}
For loop if you want to remain ignorant:

Code: Select all

for ($i=0;$i<count($thing);$i++)
{
        $val = $thing[$i];
        echo '\$thing index 1 = ' . $val . '<BR>';
}

Posted: Fri Jun 30, 2006 12:58 pm
by John Cartwright

Code: Select all

foreach ($thing as $key => $value)
{
   echo '$thing index 1 = ' . $value . '<BR>';
}
Notice how you do not have to use the array to get the value like you were doing previously.. the $key and the $value are stored inside each interation. As for wanting to use a for() loop, it's quite simple to change them. Although, you no longer will be able to use string indices, only numerical.

Code: Select all

$count = count($thing);
for ($x = 0; $x <= $count; $x++)
{  
   echo '$thing index 1 = ' . $thing[$x]. '<BR>';
}
Although I believe for()'s are a little faster, I would generally stick to foreach() when possible.

Posted: Fri Jun 30, 2006 1:01 pm
by Robert Plank
Although I believe for()'s are a little faster, I would generally stick to foreach() when possible.
Foreach is faster, proved in another thread.

http://www.robertplank.com/foreach-benchmark.php
Source: http://www.robertplank.com/foreach-benchmark.phps

Posted: Fri Jun 30, 2006 1:02 pm
by John Cartwright
Robert Plank wrote: For loop if you want to remain ignorant:
Uhh, that's not going to fly around here..

Posted: Fri Jun 30, 2006 1:02 pm
by Robert Plank
Jcart wrote:
Robert Plank wrote: For loop if you want to remain ignorant:
Uhh, that's not going to fly around here..
What isn't going to fly around where.

Posted: Fri Jun 30, 2006 1:07 pm
by daedalus__
You should listen to him.

Trust me, I just got in trouble, buahahaha

Posted: Fri Jun 30, 2006 1:10 pm
by MrPotatoes
Robert Plank wrote:
Jcart wrote:
Robert Plank wrote: For loop if you want to remain ignorant:
Uhh, that's not going to fly around here..
What isn't going to fly around where.
yeah, i'm happy someone said something.

don't talk to me or anyone like that. you don't know me personally. i want to know how to do it in a for loop. whats wrong with learning more? what's wrong with wanting to know how to do something in two different ways?

i thank you for your help but not your apparent attitude

Posted: Fri Jun 30, 2006 1:12 pm
by daedalus__
MrPotatoes is a cool guy. I even have him quoted.

Posted: Fri Jun 30, 2006 1:14 pm
by Robert Plank
MrPotatoes wrote:yeah, i'm happy someone said something.

don't talk to me or anyone like that. you don't know me personally. i want to know how to do it in a for loop. whats wrong with learning more? what's wrong with wanting to know how to do something in two different ways?

i thank you for your help but not your apparent attitude
You made it sound like you were too lazy to learn anything but for loops.

You don't know ME personally so don't try to make what I said sound like an attack.

Posted: Fri Jun 30, 2006 1:18 pm
by MrPotatoes
ok, i've said it once i'll say it again. i come from a C/C++ bacground in games. i'm used to for loops. i'm not being lazy or want to be ignorant i want to know how it's done. and honestly? i would prefer it in a for loop.

either way thank you for your information and Jcart's as well. that will make my code nicer to look at IMO.

carry on :thumbup:

[edit]anyways, the reason i asked, to be more specific, is that i'm tearing apart some code . personally for me it's easier to read for loops and if i had that it would be easier to pick apart and move around. i understand and can use foreach loops but i have to stop and think about it each time. for loops come naturally :)

Posted: Fri Jun 30, 2006 1:36 pm
by John Cartwright
Robert Plank wrote:
Although I believe for()'s are a little faster, I would generally stick to foreach() when possible.
Foreach is faster, proved in another thread.

http://www.robertplank.com/foreach-benchmark.php
Source: http://www.robertplank.com/foreach-benchmark.phps
That's odd.. I just made a quick test suite

Code: Select all

<?php

	set_time_limit(100);

	function generateArray($max)
	{
		return array_fill(0, $max, 'Test');
	}
	
	function microtime_float() {
		list($usec, $sec) = explode(" ", microtime());
		return ((float)$usec + (float)$sec);
	}
	
	function test_ForeachWithIndice($array)
	{
		foreach ($array as $key => $value) { }
	}
	
	function test_ForeachWithoutIndice($array)
	{
		foreach ($array as $value) { }	
	}
	
	function test_For($array)
	{
		$count = count($array);
		for ($x = 0; $x <= $count; $x++) { }
	}

	$start = microtime_float();
	for ($x = 0; $x < 10000; $x++)
	{	
		test_ForeachWithIndice(generateArray(1000));
	}
	$end = microtime_float();
        echo 'test_ForeachWithIndice() ' . ($end - $start) . ' seconds <br />';

	$start = microtime_float();		
	for ($x = 0; $x < 10000; $x++)
	{	
		test_ForeachWithoutIndice(generateArray(1000));
	}
	$end = microtime_float();
        echo 'test_ForeachWithoutIndice() ' . ($end - $start) . ' seconds <br />';	

	$start = microtime_float();
	for ($x = 0; $x < 10000; $x++)
	{	
		test_For(generateArray(1000));
	}
	$end = microtime_float();
        echo 'test_For() ' . ($end - $start) . ' seconds <br />';

?>
test_ForeachWithIndice() 15.040448904 seconds
test_ForeachWithoutIndice() 12.9531440735 seconds
test_For() 5.6223731041 seconds

Posted: Fri Jun 30, 2006 1:48 pm
by JayBird

Code: Select all

for ($i=sizeof($ARR); --$i>=0;);
is faster than

Code: Select all

foreach($ARR as $v);
which is faster than

Code: Select all

for ($i=0, $max=sizeof($ARR); $i < $max; $i++);
which is faster than

Code: Select all

foreach($ARR as $k => $v);

Posted: Fri Jun 30, 2006 9:38 pm
by Robert Plank
That's odd.. I just made a quick test suite
I guess it would be more fair if our code actually checked an array instead of counting up numbers.

Code: Select all

<?php

set_time_limit(0);
$arraySize = 1000;
$testRuns = 10000;

function generateArray($max)
{
        $array = array_fill(0, $max, 'Test');
        $array = array_map("uniqid", $array);
        return $array;
}
       
function microtime_float() {
        list($usec, $sec) = explode(" ", microtime());
        return ((float)$usec + (float)$sec);
}

function test_ForeachWithIndice($array)
{
        $tmp = null;
        foreach ($array as $key => $value) { $tmp = $value; }
}
       
function test_ForeachWithoutIndice($array)
{
        $tmp = null;
        foreach ($array as $value) { $tmp = $value; } 
}
       
function test_For($array)
{
        $tmp = null;
        $count = count($array);
        for ($x = 0; $x < $count; $x++) { $value = $array[$x]; $tmp = $value; }
}

$start = microtime_float();
for ($x = 0; $x < $testRuns; $x++)
{       
        test_ForeachWithIndice(generateArray($arraySize));
}
$end = microtime_float();
echo "test_ForeachWithIndice() " . ($end - $start) . " seconds <br />\n";

$start = microtime_float();          
for ($x = 0; $x < $testRuns; $x++)
{       
        test_ForeachWithoutIndice(generateArray($arraySize));
}
$end = microtime_float();
echo "test_ForeachWithoutIndice() " . ($end - $start) . " seconds <br />\n"; 

$start = microtime_float();
for ($x = 0; $x < $testRuns; $x++)
{       
        test_For(generateArray($arraySize));
}
$end = microtime_float();
echo "test_For() " . ($end - $start) . " seconds <br />\n";

?>
results:

Code: Select all

test_ForeachWithIndice() 79.1614859104 seconds
test_ForeachWithoutIndice() 69.2696409225 seconds
test_For() 71.0619039536 seconds

Posted: Fri Jun 30, 2006 10:42 pm
by Jenk
back to the question:

Code: Select all

function recursive_echo ($arr)
{
    foreach ($arr as $key => $val) {
        if (is_array($val)) {
            recursive_echo($val);
	} else {
	    echo "$key => $val\n";
	}
    }
}

$myArray = array(1,2,3,5,6,78,8,3,1,2,array(1,2,34,5));

recursive_echo($myArray);
incase you can't work it out (tongue in cheek)

Code: Select all

function recursive_echo ($arr)
{
    $c = count($arr);
    for ($i = 0; $i < $c; $i++) {
        if (is_array($arr[$i])) {
			recursive_echo($arr[$i]);
		} else {
			echo "$i => {$arr[$i]}\n";
		}
	}
}

$myArray = array(1,2,3,5,6,78,8,3,1,2,array(1,2,34,5));

recursive_echo($myArray);
And just to add to the debate of foreach vs for.. one benefit for() does not have over foreach, is if the array has keys other than integers, you will have difficulty using a for() loop. :)