Show two elements in foreach loop at each iteration?

How can we show two elements for each loop at each iteration?

For example, I have an array like this:

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

And I want to show the entries as follows:

  ab cd ef 

Any ideas?

+5
source share
4 answers

Loop through the array with for .

Print the current and current plus one value at each iteration using a counter.

Counter increase.

 <?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; } ?> 
+3
source

You can use array_chunk , this is implied for just such cases, and this is the shortest and most efficient way to do this.

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

Merges an array into arrays with size elements.

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

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

The above example outputs:

 Array ( [0] => Array ( [0] => a [1] => b ) [1] => Array ( [0] => c [1] => d ) [2] => Array ( [0] => e ) ) 
0
source

Try the following:

 <?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]; } ?> 
0
source

Source: https://habr.com/ru/post/1240144/


All Articles