Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show the two elements in foreach loop in every iteration? [duplicate]

Tags:

foreach

php

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?

like image 255
Mehar Avatar asked Jan 08 '16 07:01

Mehar


People also ask

How do you iterate two elements in a list in Python?

Use list indexing to iterate every two elements in a list. Use list indexing list[0::2] to return every second element of list , starting at index 0 .

What is difference between for loop and forEach?

For Loops executes a block of code until an expression returns false while ForEach loop executed a block of code through the items in object collections. For loop can execute with object collections or without any object collections while ForEach loop can execute with object collections only.

What does forEach loop mean?

In computer programming, foreach loop (or for each loop) is a control flow statement for traversing items in a collection. foreach is usually used in place of a standard for loop statement.

What is a forEach loop in JavaScript?

JavaScript Array forEach() The forEach() method calls a function for each element in an array. The forEach() method is not executed for empty elements.


1 Answers

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

like image 174
Annie Trubak Avatar answered Sep 30 '22 20:09

Annie Trubak