Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print() always returns 1, is there a practical use?

Tags:

php

The command echo does not return anything. But print returns 1. Always. What is the practical use of this returning 1? Sure it can be used in an expression, but isn't the expression useless if it is always true and cause use of more code?

<?php
unset($empty);
if(print ($empty)){
    echo "Yep sure thing. Print strikes again with a ", "1.";
}
?>

Shouldn't it always return the same result as below, so what's the point then?

<?php
print ($empty);
echo "Yep sure thing. Print strikes again with a ", "1.";
?>

This question is about the returning 1 and not that "Echo allows echoing more than one string separated by commas while print doesn't" etc.

like image 748
K. Kilian Lindberg Avatar asked May 23 '13 08:05

K. Kilian Lindberg


1 Answers

print always returns one in the real world. If you are trying to perform Inception, you can devise a print function that always returns zero. That way, you can check to see if you are in a dream or the real world.

In reality however, the usage of print's return value is the same as simply using true. Infinite while loops, printing debugging information, etc. are all very compelling uses but they are bad design (verging on insane) and should be avoided.

like image 136
ose Avatar answered Sep 28 '22 08:09

ose