We had use the PHP echo statement to output text to the web browser in the previous lesson.
PHP echo is actually a language construct not a function.so you don't need to use parenthesis with it.
<?php echo "Hello World"; // multiple arguments echo 'multiple ', 'parameters', PHP_EOL; // concatenation string echo 'concatenation ' . 'string '.PHP_EOL; $some_var = true; echo $some_var ? 'true': 'false'; // changing the statement around ?>
if you want to use more than one parameters, the parameters must not be enclosed within parentheses.
<?php // multiple arguments echo 'multiple ', 'parameters'; // Invalid echo ('multiple ', 'parameters'); // Parse error: syntax error, unexpected ',' ?>
the echo statement can display anything that can be displayed to the browser,such as string,multi line strings, escaping characters, variable, array etc.
<?php echo "Hello World"; ?>
Output:
Hello World
<?php echo 'You can also have embedded newlines in strings this way as it is okay to do'; ?>
Output:
You can also have embedded newlines in strings this way as it is okay to do
<?php echo '<h2 class="tool-title">PHP</h2>'; echo '<div class="tool-desc">PHP:Hypertext Preprocessor is a popular scripting language that is especially suited to web development.</div>'; ?>
<?php // Defining variables $str = "Hello World!"; $int = 798; $arr = array(1,2,3); // Displaying variables echo $str; echo "<br>"; echo $int; echo "<br>"; foreach($arr as $value){ echo $value." "; } ?>
Output:
Hello World! 798 1 2 3
You can also place variables inside of double-quoted strings.
The PHP parsing engine will grab the string value of that variables and replace it in the string.
Note: use double-quotes. single-quotes won't work.
<?php $site = "Lautturi"; echo "Hello $site".PHP_EOL; // This won't work echo 'Hello $site'.PHP_EOL; ?>
Output:
Hello Lautturi Hello $site
If you want to output a string that includes quotations, either use an apostrophe ( ' ) or escape your quotes. i.e. "
<?php // This won't work because of the string includes quotations echo "<h2 class="tool-title">Lautturi PHP tutorial</h2>"; // Works, because we escaped the quotes! echo "<h2 class=\"tool-title\">Lautturi PHP tutorial</h2>"; // Works, because we used an apostrophe ' echo "<h2 class='tool-title'>Lautturi PHP tutorial</h2>"; // Works, because we used an apostrophe ' echo '<h2 class="tool-title">Lautturi PHP tutorial</h2>'; ?>