Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Loop two arrays if index of one is last rewind array

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

like image 322
Spy Avatar asked Dec 24 '22 00:12

Spy


2 Answers

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;
}
  • Live demo at https://3v4l.org/LmYRk
like image 171
Qirel Avatar answered Jan 13 '23 05:01

Qirel


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
like image 45
Unamata Sanatarai Avatar answered Jan 13 '23 03:01

Unamata Sanatarai