Forum Moderators: coopster

Message Too Old, No Replies

How to cycle through arrays

         

ocon

9:26 pm on May 6, 2010 (gmt 0)

10+ Year Member Top Contributors Of The Month



Hello, I have three variables, one of which is a mulitarray:

$enough_gas_to_travel=35;
$margin_of_error=3;

$gas_stations=array(
array("name"=>"Chevron","distance"=>15),
array("name"=>"Texaco","distance"=>21),
array("name"=>"Shell","distance"=>23),
...);

How can I cycle through the array? I'd like to figure out the possible outcomes:

if($gas_stations within $enough_gas_to_travel==1){ list the gas station }
else if($gas_stations within $enough_gas_to_travel+$margin_of_error==1){ list the gas station }
else if($gas_stations within $enough_gas_to_travel>1){ list the gas stations }
else if($gas_stations within $enough_gas_to_travel+$margin_of_error>1){ list the gas stations}
else{ number to towing service }

Readie

9:48 pm on May 6, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Quite simple, just use a for loop:
$count = count($gas_stations);
for($i = 0; $i < $count; $i++) {
echo '<br>' . $gas_stations[$i]['name'] . ' - ' . $gas_stations[$i]['distance'];
}
Will output the following:

Chevron - 15
Texaco - 21
Sheel - 23
...

So it's just a simple logical step to your ifs - have them inside the for() loops curly braces - that for loop will execute the code inside the curly braces for every single entry in the array.