Home > OS >  print break line after n number of iterations
print break line after n number of iterations

Time:11-07

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

CodePudding user response:

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()

<?php

$split = [4, 2, 4];
$courses = ['HTML', 'JS', 'CSS', 'VueJS', 'ReactJs', 'PHP', 'Ruby', 'Python', 'Java', 'C#'];
foreach($courses as $key => $value){
    echo $value;
    if (in_array($key, $split)) {
        echo '<br>';
    }
 }
 ?>

CodePudding user response:

You need to track next items order after found it.

<?php

$split = [4, 2, 3];
$courses = ['HTML', 'JS', 'CSS', 'VueJS', 'ReactJs', 'PHP', 'Ruby', 'Python', 'Java', 'C#'];

$split_position = $reIndexValue = 0;
$elements = [];

foreach($courses as $index => $name) {
    $reIndexValue  ;

    if(is_int($split_position) && $reIndexValue == $split[$split_position]) {
        
        $name = $name.'<br>';
        $split_position = isset($split[$split_position   1])?    $split_position : false;
        $reIndexValue = 0;
        
    }
    
    $elements[] = $name;
}

echo implode (' ',$elements);
  •  Tags:  
  • php
  • Related