Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call php function inside echo?

Tags:

php

My data are usually taken from mysql however that's not the issue. My problem is i want to be able to call few functions inside an echo. I dont even know if it is possible. Im almost new to php Please any help is appreciated.

<?php
     echo"
        <div class='container'>
          <select name='science'>
         <?php science_facts(); ?>
          </select>
        </div>
    ";      
?>

or

<?php
    echo"
          <div class='container'>
            <select name='science'>
           science_facts();
           </select>
        </div>  
   ";   
?>

Both not working.

like image 782
Anonymous Boy Avatar asked Sep 19 '25 04:09

Anonymous Boy


1 Answers

You have to break up the string into its static and dynamic parts. There are numerous ways to do this but the two most common are to use multiple echo statements:

echo "<div class='container'>";
echo "<select name='science'>";
echo science_facts(); // Note no quotes!
echo "</select>";
echo "</div>";

Or use the . string concatenation operator to join strings on the fly:

echo "<div class='container'>" .
    "<select name='science'>" .
    science_facts() .
    "</select>" .
    "</div>";

Or, the same in one line:

echo "<div class='container'><select name='science'>" . science_facts() . "</select></div>";

Or start/stop PHP execution explicitly:

...
?>
<div class='container'>
<select name='science'>
<?php echo science_facts(); ?>
</select>
</div>
<?php
...

(Note: This assumes that your science_facts() function returns its output rather than echoing it.)

like image 64
Alex Howansky Avatar answered Sep 20 '25 20:09

Alex Howansky