The goal is to "break line" after each split.
I have two arrays:
$split = [4, 2, 4];
$courses = ['HTML', 'JS', 'CSS', 'VueJS', 'ReactJs', 'PHP', 'Ruby', 'Python', 'Java', 'C#'];
As you can see I have the first array
called split, and the second array
called courses, I want to add <br>
after each split
I want to loop over $courses
and after the 4 items I print <br>
. Also after 2 items I print another <br>
Note: I can have more values in my $split
array, that’s why I don’t want to use
foreach($courses as $key => $value){
echo $value;
if ($key == 4 OR $key == 2){
echo '<br>';
}
}
My code is not working fine because I can’t use a lot of OR
with if statements
, because I can have a lot of split in my $split
array
Is there any clean and best way to loop over $courses
and print <br>
after 4
loop and after 2
and after 4
and so on, it depends on how many split I have in my $split
3
Answers
This will get the job done, bear in mind that arrays start at 0, not 1. so it would break on the 3rd and 5th item not 2nd and 4th.
More on in_array()
You need to track next items order after found it.
The following code will first echo a line break after 4 iterations, then it will echo a line break after 2 more iterations, and then it will echo another line break after 4 more iterations. (The code will continue for any specified sequence in the $split array)
I added 2 other variables "Pascal" and "Fortran" into the $courses array to test the behavior