In every programming language available today, there is usually more than one way to display output to the screen. PHP has two methods:
echo
statements.print
statements.echo
statementsThis is the most commonly used of the two functions used to display output in PHP. echo
can be used with or without parentheses and can take several strings and variables concatenated together.
<?php$toDisplay = 200;$$toDisplayMyName = ',You will see me on screen';$insideHtml = ",An Html paragragh,";//can display content of a variable be it a string or notecho $toDisplay;echo $$toDisplayMyName;//used to dispay a string which must be qouted "" or '';echo ",Now is double qoute";echo ',Now is double qoute';// can display concatenated strings and variables;echo ",You can display string & variables".$toDisplay;//can also be used to echo html codes/components/* echo '<P>'$insideHtml'</p>'This won't exucute properly here becuase thisplayground only understand php code.*/;//using it with parenthesesecho (",used with parentheses");// Can take multiple comma separated parametersecho $insideHtml,$$toDisplayMyName,$toDisplay;?>
The code above includes scenarios of how we can use the echo
statement.
print
statementsThe print
statement in PHP is what you might call a pseudo function. This is because it returns a value 1
like a function, but it is not callable like functions are.
Although the print
statement can be used in almost the same way as the echo
statement in the code above, it cannot print multiple parameters. The print
statement’s main importance is that it can be used inside expressions and even in conditions, unlike the construct echo
, which must be used at the start of a new line.
<?php$m = 4;$n = 5;//you can say doecho print $n + $m;/*where 1 in the output of above code isthe return value of print.*///but notprint echo $n + $m;/*Above will throw an error*comment it out to see the output of others*/?>
You can also use the print
statement to do print out to the screen inside your conditions, as shown below.
<?php/*This code will increment the counter withthe return value of the print statement whileprinting the curent value of the counter.*//*the echo willdisplay the final value of the counter*/for ( $i = 0; $i < 10; $i += print "$i," );{echo $i;}?>
Try exchanging echo
for print
and vice versa in the code above and see what happens.
Echo | ||
1 | Can output multiple parameters | Only outputs concatenated strings or parameters |
2 | Has no return value | Has a return value of 1 |
3 | Returns nothing, and is slightly faster | Has a return value, and slows down slightly |
4 | Can't be used within expressions | Can be used within expressions and conditions |