PHP echo and print Statements
PHP echo and print Statements
Echo and print are more or less the same. They are both used to output data to the screen.
The differences are small: echo has no return value while print has a return value of 1 so it can be used in expressions. echo can take multiple parameters (although such usage is rare) while print can take one argument. echo is marginally faster than print.
The PHP echo Statement
PHP echo is a language construct, not a function. Therefore, you don't need to use parenthesis with it. But if you want to use more than one parameter, it is required to use parenthesis.The echo statement can be used with or without parentheses: echo or echo().
Some important points that you must know about the echo statement are:
- echo is a statement, which is used to display the output.
- echo can be used with or without parentheses: echo(), and echo.
- echo does not return any value.
- We can pass multiple strings separated by a comma (,) in echo.
<?php
echo "PHP is Fun!
";
echo "Hello world!
";
echo "I'm about to learn PHP!
";
echo "This ", "string ", "was ", "made ", "with multiple parameters.";
?>
The following example will output the sum of two variables using echo statement:
<?php
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
$x = 5;
$y = 4;
echo "" . $txt1 . "
";
echo "Study PHP at " . $txt2 . "
";
echo $x + $y;
?>
The PHP print Statement
Like PHP echo, PHP print is a language construct, so you don't need to use parenthesis with the argument list. Print statement can be used with or without parentheses: print and print(). Unlike echo, it always returns 1.The print statement can be used with or without parentheses: print or print().
Some important points that you must know about the echo statement are:
- print is a statement, used as an alternative to echo at many times to display the output.
- print can be used with or without parentheses.
- print always returns an integer value, which is 1.
- Using print, we cannot pass multiple arguments
- print is slower than the echo statement.
Variable with global scope:
<?php
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
$x = 5;
$y = 4;
print "" . $txt1 . "
";
print "Study PHP at " . $txt2 . "
";
print $x + $y;
?<
<?php
$x = 5;
$y = 10;
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}32
myTest();
echo $y; // outputs 15
?>