Question

This is my php code

$arr = array(1,2,3,4);
function mypic($arr){
    foreach ($arr as $pic){
        echo "<img src='img/$pic.png'/>";       
    }
}


$i = 1;
while($i < 10){
    echo "<p>".mypic($arr)."</p>";
    $i++;
}

the output I got is

<img src="img/1.png">
<img src="img/2.png">
<img src="img/3.png">
<img src="img/4.png">
<p></p>
<img src="img/1.png">
<img src="img/2.png">
<img src="img/3.png">
<img src="img/4.png">
<p></p>

However, I need to get the below output

<p>
<img src="img/1.png">
<img src="img/2.png">
<img src="img/3.png">
<img src="img/4.png">
</p>

How do I fix it? Thanks

Was it helpful?

Solution

Try this:

$arr = array(1,2,3,4);
function mypic($arr){
    foreach ($arr as $pic){
        echo "<img src='img/$pic.png'/>";       
    }
}

$i = 1;
while ($i < 10) {
   echo "<p>";
   mypic($arr);
   echo "</p>";
   $i++;
}

Alternatively, you can have you mypic() function return a string rather than print it:

$arr = array(1,2,3,4);
function mypic($arr){
    $str = "";
    foreach ($arr as $pic){
        $str .= "<img src='img/$pic.png'/>";       
    }
    return $str;
}

$i = 1;
while ($i < 10) {
   echo "<p>";
   echo mypic($arr);
   echo "</p>";
   $i++;
}

OTHER TIPS

You may also use:

$arr = array(1,2,3,4);
function mypic($arr){
    $_str = '';
    foreach ($arr as $pic){
        $_str .= "<img src='img/$pic.png'/>";       
    }
    return $_str;
}

$i = 1;
while ($i < 10) {
   echo "<p>".mypic($arr)."</p>";
   $i++
}

Or:

$arr = array(1,2,3,4);
function mypic($arr){
    $_arr = array();
    foreach ($arr as $pic){
        $_arr[] = "<img src='img/$pic.png'/>";       
    }
    return implode(PHP_EOL, $_arr);
}

$i = 1;
while ($i < 10) {
   echo "<p>".mypic($arr)."</p>";
   $i++
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top