Reputation: 5758
I know echo()
and print()
do the same thing. but print has a return value of (int) 1
.
The question is:
Upvotes: 14
Views: 7210
Reputation: 1
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
Upvotes: -1
Reputation: 63576
You can the return value in cases where you actually have to count.
Example:
for ( $i = 0; $i < 10; $i += print "$i<br>" );
You can combine printing and counting here.
Upvotes: 0
Reputation: 11635
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();
}
Just make sure the maintainers don't know where you live
Upvotes: 3
Reputation: 37975
It's just a little feature that allows you to use print in conditions, like :
if ((print "angry") && (print "mammoth") || (print "will stomp you"))
{
// always executed
}
Now what's the use of this ? No idea.
Upvotes: 2
Reputation: 50928
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.)
Upvotes: 6
Reputation: 145502
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");
Upvotes: 11