Return not working in foreach, displaying just one element?

Here is a quick fix.

You can use concatenate.

A simple example:

1
2
3
4
$a = 'cristi ';
$a .= 'rocks';
 
echo $a;

will display ‘cristi rocks’;

You can use the same thing inside a foreach statement. Here is a good example.

2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<div class="row">
<?php
function images(){
$pictures = array("https://static.pexels.com/photos/104827/cat-pet-animal-domestic-104827.jpeg",
"https://static.pexels.com/photos/126407/pexels-photo-126407.jpeg",
"http://www.rd.com/wp-content/uploads/sites/2/2016/02/06-train-cat-shake-hands.jpg");
 
$display = '';
foreach ($pictures as $picture){
	$display .= '<div class="col-xs-12 col-md-3"><img src="'.$picture.'" class="img-responsive"></div>';	
}
return $display;
}
 
$var = images();
echo $var;
?>
</div>

As you see, we concatenate $display from inside the foreach statement so it won’t display only one item.

Coding

ADD A COMMENT: