Home » Php » php – Show the two elements in foreach loop in every iteration?

php – Show the two elements in foreach loop in every iteration?

Posted by: admin July 12, 2020 Leave a comment

Questions:

How we can show the two elements in for each loop in each iteration?

For example I have an array like this:

$arr = array('a', 'b', 'c', 'd','e','f');

And want to show the records like this:

  a-b
  c-d
  e-f

Any ideas?

How to&Answers:

Loop over the array with for.

Print the current and current plus one value in each iteration by counter.

Increment the counter.

<?php
$arr = array('a', 'b', 'c', 'd','e','f');
$i=0;
$len = count($arr);
for ($i=0; $i< $len; $i++) { // We could have used count($arr) 
//instead of $len. But, it will lead to 
//multiple calls to count() function causing code run slowly.
    echo "<br/>".$arr[$i] . '-' . $arr[$i+1];
  ++$i; 
}
?>

Answer:

You can use array_chunk, it is meant exactly for these kind of cases and it’s the shortest and most efficient way to do it.

$arr = array('a', 'b', 'c', 'd','e','f');
foreach(array_chunk($arr , 2) as $val) {
    echo implode('-', $val)."\n";
}

Chunks an array into arrays with size elements.

More details:
http://php.net/manual/en/function.array-chunk.php

Demo: https://3v4l.org/BGNbq

Answer:

<?php
$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2));
?>

The above example will output:

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
            [1] => d
        )

    [2] => Array
        (
            [0] => e
        )

)

Answer:

Try this:

<?php
  $array = array('a', 'b', 'c', 'd','e','f');
  $length = count($array);
  for ($i=0; $i< $length; $i+2) {
      echo "<br/>".$arr[$i] . '-' . $arr[$i+1]; 
  }
?>