How to call php function inside echo?

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.

Comment (2)

Jese Leos

August 29, 2024

Verified user

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.)

Jese Leos

August 29, 2024

Verified user

In my case puting function inside echo resulted in displaying result of a function before input tag (weird). My solution was end echo function than trigger function and continue echo. Not working (displaying result of function before 'input' tag): echo '<input type="checkbox" class="custom-control-input" id="zabezpieczenie' . $idZabezpieczenia . '" name="zabezpieczenie' . $idZabezpieczenia . '" value="zabezpieczenie' . $idZabezpieczenia . '" onclick="dodaj_czynnosc(this.value, this.id)"'.checkChecked('zabezpieczenie' . $idZabezpieczenia).'>'; Working (displaying result of function inside 'input' tag): echo '<input type="checkbox" class="custom-control-input" id="zabezpieczenie' . $idZabezpieczenia . '" name="zabezpieczenie' . $idZabezpieczenia . '" value="zabezpieczenie' . $idZabezpieczenia . '" onclick="dodaj_czynnosc(this.value, this.id)"'; checkChecked('zabezpieczenie' . $idZabezpieczenia); //displays checked echo '>';

You’ll be in good company