using for loop with an array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
pelegk2
Forum Regular
Posts: 633
Joined: Thu Nov 27, 2003 5:02 am
Location: Israel - the best place to live in after heaven
Contact:

using for loop with an array

Post 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
visionmaster
Forum Contributor
Posts: 139
Joined: Wed Jul 14, 2004 4:06 am

Re: using for loop with an array

Post 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;
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post 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
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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.
User avatar
patrikG
DevNet Master
Posts: 4235
Joined: Thu Aug 15, 2002 5:53 am
Location: Sussex, UK

Post by patrikG »

array_walk()

same source:

foreach()

list()

Very good resource that.
Post Reply