I have a PHP function that I'm using to output a standard block of HTML. It currently looks like this:
<?php function TestBlockHTML ($replStr) { ?> <html> <body><h1> <?php echo ($replStr) ?> </h1> </html> <?php } ?>
I want to return (rather than echo) the HTML inside the function. Is there any way to do this without building up the HTML (above) in a string?
While HTML and PHP are two separate programming languages, you might want to use both of them on the same page to take advantage of what they both offer. With one or both of these methods, you can easily embed HTML code in your PHP pages to format them better and make them more user-friendly.
A function can return a value using the return statement in conjunction with a value or object. return stops the execution of the function and sends the value back to the calling code. You can return more than one value from a function using return array(1,2,3,4).
Echo is for display, while return is used to store a value, which may or may not be used for display or other use.
Using these simple steps, we can easily add the PHP code. Step 1: Firstly, we have to type the Html code in any text editor or open the existing Html file in the text editor in which we want to use the PHP. Step 2: Now, we have to place the cursor in any tag of the <body> tag where we want to add the code of PHP.
You can use a heredoc, which supports variable interpolation, making it look fairly neat:
function TestBlockHTML ($replStr) { return <<<HTML <html> <body><h1>{$replStr}</h1> </body> </html> HTML; }
Pay close attention to the warning in the manual though - the closing line must not contain any whitespace, so can't be indented.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With