Currently, the code below only returns the first letter of the strings in $pizzas[]
:
$total = 0;
$pizzas = array('kebabpizza' => 80, 'calzone' => 60, 'vesuvio' => 60);
foreach ($pizzas as $pizza => $price) {
for($i = 0; $i < count($pizza); $i ++) {
echo $pizza[$i] . " - $price<br>";
break;
}
$total +=$price;
}
echo "Your order is gonna cost you $total kr<hr>";
Output:
k - 80
c - 60
v - 60
Your order is gonna cost you 200 kr
When you do your foreach
loop, you're iterating over your array. When you say as $pizza => $price
, the variable $pizza
is assigned the key of the current array item you're looking at and $price
is assigned the value. So in the first iteration of the loop $pizza
is kebabpizza
and $price
is 80
.
Next, you're doing a for
loop over the string kebabpizza
(or whatever the key of the array is at that time). When you try to access $pizza[$i]
in the first iteration of the for
loop you're getting the letter k
in kebabpizza
. You're then echo
ing out k
and then the price of the pizza.
Following that you have a break
statement which will terminate the inner for
loop and the outer foreach
loop will continue. That's why you're seeing only the first letters.
Assuming you want to output the name of the pizza and the price, then you don't need the inner for
loop at all:
$total = 0;
$pizzas = array('kebabpizza' => 80, 'calzone' => 60, 'vesuvio' => 60);
foreach ($pizzas as $pizza => $price) {
echo "$pizza - $price<br>";
$total +=$price;
}
echo "Your order is gonna cost you $total kr<hr>";
Why are you looping over $pizza
$total = 0;
$pizzas = array('kebabpizza' => 80, 'calzone' => 60, 'vesuvio' => 60);
foreach ($pizzas as $pizza => $price) {
echo $pizza . " - " . $price . "<br>";
$total +=$price;
}
echo "Your order is gonna cost you $total kr<hr>";
Beacuse you are looing in the $pizza variable that is a string(so an array of chars) instead of just using it in the foreach cycle
$total = 0;
$pizzas = array('kebabpizza' => 80, 'calzone' => 60, 'vesuvio' => 60);
foreach ($pizzas as $pizza => $price) {
echo $pizza . " - $price<br>";
}
$total +=$price;
echo "Your order is gonna cost you $total kr<hr>";
clear example
$total = 0;
$pizzas = array('kebabpizza' => 80, 'calzone' => 60, 'vesuvio' => 60);
foreach ($pizzas as $key => $value) {
echo $key . " - $value<br>";
}
$total +=$price;
echo "Your order is gonna cost you $total kr<hr>";
That's because you're trying to iterate over a string with your second loop.
Your first loop will iterate over each element in the array:
foreach ($pizzas as $pizza => $price) { ...
Will iterate over these items
- kebabpizza => 80
- calzone => 60
- vesuvio => 60
In your inner (second) loop (for($i = 0; $i < count($pizza); $i ++)
), you will then actually try to iterate over each character in the key element
k[0]
e[1]
b[2]
a[3]
...
If you just skip the inner loop altogether and print $pizza
instead you should be fine
foreach ($pizzas as $pizza => $price) {
echo $pizza . " - $price<br>";
}
$total +=$price;