DEV Community

AquaCat
AquaCat

Posted on

【PHP】How to get index number when using "foreach"?

How do you get index number of array while iterating it with "foreach"?

Eventually, you need to create an variable for
index number to use in foreach.

Here is an example.

//Array of menu and price (eg. $5 for 1 Big Mac)
$menu_price=a["Big Mac"=>5,"Chicken Nuggets"=>3,"Egg McMuffin"=>2];

//Array of number of orders for each menu (eg. 10 Big 
Macs are ordered.)
$number_of_orders=[10,8,6];

//Variable for index number
$i=0;

//Calculate the total price
function calculate($price,$number){
  return $price*$number;
}

foreach($menu_price as $menu=>$price){
  echo "{$number_of_orders[$i]} {$menu} cost $"
.calculate($price,$number_of_orders[$i]).".";
  echo "<br/>";
  $i++;
}
Enter fullscreen mode Exit fullscreen mode

What you will get is as below.

10 Big Mac cost $50.
8 Chicken Nuggets cost $24.
6 Egg McMuffin cost $12
Enter fullscreen mode Exit fullscreen mode

Top comments (0)