I know echo() and print() do the same thing. but print has a return value of (int) 1.
The question is:
- Why it always returning (int) 1 ?
- What we can do with returning (int) 1 ?
I know echo() and print() do the same thing. but print has a return value of (int) 1.
The question is:
print is a function and can be used in expressions, while echo is a language construct that can only be used at the start of the line.
echo print(print(print(print(123)))), print(4); The real use case for having print available as a function is to allow it to be used in expressions. For example as debug feature:
if (($a == $b) and print("It's true") and $c) { Or even
return TRUE and print("right"); Most likely to signify success, so you could interpret it as the value TRUE.
In future code, instead of doing
$i++; you can do
$i = $i + print("Hello World!\n"); (Minor side-effects may apply.)
As others already mentioned, print is pseudo-function (returns a value but not a real function), which makes its use valid in expressions. So you can write quirky code like this to confuse the maintainers :)
$success = doSomethingThatCanPossiblyFail(); if ($success || !(print "Failed to do that! Not going to do the follow up")){ //success nowDoTheFollowupThing(); } print always return 1 if the print work successfully. else it will return 0. and in echo we can show the successful or unsuccessful of print function.
echo print(1);// 11
if we write print(1) alone it will print to us 1 .
print(1);// 1
one example for better knowing.
function sum($a,$b) { echo $a+$b; if($a+$b == true) { return 1; } else{ return 0;} } // now we call the function
sum(3,1);//4 echo "<br>"; echo sum(3,1);// 41 echo "<br>"; sum('abc','xyz');// 0 echo "<br>"; echo sum('abc','xyz');//00 this code work like print function