I have two arrays. The first array is names and it has 5 names. The second array is groups and it has 3 groups. I want to loop through both of the arrays and set each index name to the index group. If the group index finishes I want to restart the second array.
I tried reseting the group index to 0 if it reaches the last item but it doesn't work.
$names = [
'John',
'Jane',
'George',
'Jim',
'Jack'
];
$groups = [
'1',
'2',
'3'
];
foreach ($names as $index => $name) {
$result = "The student: " . $name . " belongs to the: " .$groups[$index]. "group" ;
echo ($result);
echo "<br>";
echo "<br>";
}
When it reaches the fourth name item, the group item should be 1. Is there a way to do such think?
Expected outcome
John - 1
Jane - 2
George - 3
Jim - 1
Jack - 2
Thank you in advance
We assume that the array is numerically indexed (starting from 0), and that there are no indexes that are skipped (i.e. the $group
array is always defined as range(1, $n);
).
Then you can use the modulus operator %
against the length of that array, as shown below.
foreach ($names as $index => $name) {
$result = "The student: " . $name . " belongs to group " .$groups[$index % count($groups)]. ".\n";
echo $result;
}
You can modulo %
the groups indexing.
$groups[$index % sizeOf($groups)]
<?php
$names = [
'John',
'Jane',
'George',
'Jim',
'Jack'
];
$groups = [
'1',
'2',
'3'
];
foreach ($names as $index => $name) {
$result = "The student: " . $name . " belongs to the: " .$groups[$index%sizeOf($groups)]. "group" ;
echo ($result);
echo "<br>";
echo "<br>";
}
result: https://3v4l.org/LnOHAK
The student: John belongs to the: 1group<br><br>The student: Jane belongs to the: 2group<br><br>The student: George belongs to the: 3group<br><br>The student: Jim belo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With