Page 1 of 1

using for loop with an array

Posted: Sun Feb 13, 2005 4:22 am
by pelegk2
how can i go over an array like :
array("a" => "orange", "b" => "banana", "c" => "apple");
with a for loop?
(i preffer at the moment a for loop and not a foreach loop)
thnaks i nasvance
peleg

Re: using for loop with an array

Posted: Sun Feb 13, 2005 5:24 am
by visionmaster
Try it out this way. I had to change your key names to get my for loop to work.

Code: Select all

$arrFruits = array("m1" => "orange", "m2" => "banana", "m3" => "apple"); 

/*while ( $element = each($arrFruits) )
{
		echo $element&#1111;'1']."<br>";
		# Alternatively use	
		//echo $element&#1111;'value']."<br>";

&#125; */


$number = count($arrFruits);
for($i=0;$i<$number;$i++)&#123;
	$element = "m".$i;
	echo $arrFruits&#1111;$element]."<br>";
&#125;

Posted: Sun Feb 13, 2005 7:40 am
by Chris Corbyn
pelegk2 does your array strictly go up in terms of a,c,c,d,e,f,g..... or are the key name somewhat random?

Build a new array which maps a=>1, b=>2, c=>3 etc and then use that to decide the key name to use when looping

EDIT: You'll need to reverse those key names actually... so 1=>a, 2=>b etc

Posted: Sun Feb 13, 2005 9:11 am
by feyd

Code: Select all

$keys = array_keys($array);
$values = array_values($array);
for( $x = 0, $y = count($keys); $x < $y; $x++ )
&#123;
  echo $keys&#1111;$x];
  echo $values&#1111;$x];
  echo $array&#1111;$keys&#1111;$x]];
&#125;
please think.

Posted: Sun Feb 13, 2005 3:00 pm
by patrikG
array_walk()

same source:

foreach()

list()

Very good resource that.