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?
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 .
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.
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.
JavaScript Array forEach() The forEach() method calls a function for each element in an array. The forEach() method is not executed for empty elements.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With