Hi I'm trying to make an ordered list print out from an array. This is my code as of now:
<?php
$Salespeople = array(
"Hiroshi Morinaga"=>57,
"Judith Stein"=>44,
"Jose Martinez"=>26,
"Tyrone Winters"=>22,
"Raja Singh"=>21);
foreach ($Salespeople as $Salesperson) {
echo key($Salespeople) . ": $Salesperson cars<br />";
next($Salespeople);
}
?>
the problem i have is that the outcome is this:
Judith Stein: 57 cars
Jose Martinez: 44 cars
Tyrone Winters: 26 cars
Raja Singh: 22 cars
: 21 cars
How can i make it so it shows all the names and instead print out like this?
Hiroshi Morinaga: 57
Judith Stein: 44 cars
Jose Martinez: 26 cars
Tyrone Winter: 22 cars
Raja Singh: 21 cars
Thank you.
do want something like this?
foreach($Salespeople as $fullname => $cars)
{
echo $fullname . ": " . $cars . " cars<br />";
}
Use foreach just simplier:
foreach ($Salespeople as $Salesperson => $Cars) {
echo $Salesperson . ": $Cars cars<br />";
}
foreach
will iterate over the list itself - you don't need to use key
or next
.
foreach ($Salespeople as $name => $number) {
echo $name . ": $number cars<br />";
}
Just for fun, you could also use array_map
:
function echoSalesperson($v) {
echo $v . ": $Salesperson cars<br />"
}
array_map($Salespeople,'echoSalesperson');