Two elements print in one foreach loop than the start of the next loop

I have an array

$foo = array(1,2,3,4,5,6,7,8,9); 

when i use foreach loop for this

 foreach($foo as $val): print '<li>'.$val.'</li>'; endforeach 

Out put is

 <li> 1 </li> <li> 2 </li> <li> 3 </li> <li> 4 </li> <li> 5 </li> 

But I want to put something like this

 <li> 1, 2 </li> <li> 3, 4 </li> <li> 5, 6 </li> <li> 7, 8 </li> 

Is it possible?

+4
source share
4 answers

This might be what you need:

 foreach($foo as $key=>$val) { if ($val&1) { echo '<li>' . $val; if($key == (count($foo)-1)){ echo '</li>'; } } else { echo ',' . $val . '</li>'; } } 
+1
source
 $foo = array(1,2,3,4,5,6,7,8,9); foreach (array_chunk($foo, 2) as $chunk) { echo "<li>" . implode(', ', $chunk) . "</li>\n"; } 
+4
source

For php you can:

 for($i=0;$i<count($foo);$i+=2) { echo "<li>{$foo[$i]}, {$foo[$i+1]}</li>"; } 
+2
source

Please try the following:

 $foo = array(1,2,3,4,5,6,7,8,9); $i=1; $firstElement = ""; foreach($foo as $val): if($i%2==0) { print '<li>'.$firstElement.','.$val.'</li>'; } else { $firstElement = $val; } $i++; endforeach 
0
source

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


All Articles