I was trying to assign each seller their monthly points, based on the amount of products they sell. The numbers, however, are just an example. This is my code so far:
$sellers = array(
'Edvin' => 10,
'Julio' => 9,
'Rene' => 8,
'Jorge' => 7,
'Marvin' => 6,
'Brayan' => 5,
'Sergio' => 4,
'Delfido' => 3,
'Jhon' => 2
);
$a = 1;
foreach ($sellers as $seller => $points) {
while ($a < 4) {
echo "The seller top " . $a . " is " . $sellers[$a - 1] . ' with ' . $points[$a] . '<br>';
$a++;
}
}
I am trying to output this:
The seller top 1 is Edvin with 10<br>
The seller top 2 is Julio with 9<br>
The seller top 3 is Rene with 8<br>
You only want to access the first three elements, so slice the array before looping, you can increment the counter as you iterate.
Code: (Demo)
$sellers = array('Edvin' => 10, 'Julio' => 9, 'Rene' => 8, 'Jorge' =>7, 'Marvin' => 6,
'Brayan' => 5, 'Sergio' => 4, 'Delfido' => 3, 'Jhon' => 2);
$i = 0;
foreach (array_slice($sellers, 0, 3) as $seller => $points) {
echo "The seller top " . ++$i . " is $seller with $points<br>";
}
Output:
The seller top 1 is Edvin with 10<br>
The seller top 2 is Julio with 9<br>
The seller top 3 is Rene with 8<br>
If you want to control the loop with the counter and omit the array_slice()
call, you will need to write a loop break.
$i = 0;
foreach ($sellers as $seller => $points) {
echo "The seller top " . ++$i . " is $seller with $points<br>";
if ($i == 3) break;
}
Why are you using a While Loop inside a foreach Loop ?
You can do this:
$sellers = array(
'Edvin' => 10,
'Julio' => 9,
'Rene' => 8,
'Jorge' => 7,
'Marvin' => 6,
'Brayan' => 5,
'Sergio' => 4,
'Delfido' => 3,
'Jhon' => 2
);
$a = 1;
foreach (array_flip($sellers) as $points => $seller) {
if ($a < 4) {
echo "The seller top " . $a . " is " . $seller . ' with ' . $points . '<br>';
$a++;
}
}
If you want to use a while loop you can do this to:
$sellers = array(
'Edvin' => 10,
'Julio' => 9,
'Rene' => 8,
'Jorge' => 7,
'Marvin' => 6,
'Brayan' => 5,
'Sergio' => 4,
'Delfido' => 3,
'Jhon' => 2
);
$a = 0;
// Get Associative Keys
$keys = array_keys($sellers);
while($a < 3){
// Get Assoc INDEX at position
$index = $keys[$a];
echo "The seller top " . ($a+1) . " is " . $index . ' with ' . $sellers[$index] . '<br>';
$a++;
}