0

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

1
  • 6
    You need to have mypic() return a string, not echo it. Commented Mar 3, 2014 at 22:48

2 Answers 2

2

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++;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much, will tick it :-)
Definitely! waiting for the time to allow me to tick! ;)
1

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++
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.