Print () always returns 1, is there any practical use?

The echo command returns nothing. But printing returns 1. Always. What is the practical use of this return 1? . Of course, it can be used in an expression, but it is not useless if it is always true , and causes the use of more code?

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

Should 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 returning 1, and not that "Echo allows you to repeat multiple lines separated by commas until printing is completed," etc.

+6
source share
4 answers

print always returns one in the real world. If you are trying to throw an Inception, you can create a print function that always returns zero. This way you can check if you are in a dream or in the real world.

In reality, however, using the return value of print same as using true . Endless while loops, printing debug information, etc. - All this is a very attractive use, but they are poorly designed (bordering on the insane) and should be avoided.

+3
source

Since the result is always true, you can link it together in the expression as follows:

 if (print('debug stuff') && $a == 1) { // do stuff } elseif (print('debug another') && $a > 56) { // do stuff } 

As conditions are evaluated, it will work as a kind of debugging that does not affect the result.

Or, used in an infinite loop:

 while(print('still in the loop')) { // do something very exciting } 

Although these are some things you could not do with echo (this will cause a parsing error), its usefulness is mainly limited to testing and debugging , not the operational stage.

+2
source

I do not see any useful expressions. But I can create something strange:

For short circuit on the circuit:

 for($i=0; $i<100; $i+=print($i.')<br/>')) ; 

While the loop print counter:

 //$result is some db result $rowCounter = 0; while($row = $result->fetchAssoc()) { $rowCounter += print($row['column']); } 
+1
source
 **echo** No return value Outputs one or more strings separated by commas eg echo "String 1", "String 2" **print** Returns 1, so it can be used in an expression Outputs only a single string 

eg. if ((print "foo") && (print "bar"))

0
source

Source: https://habr.com/ru/post/945663/


All Articles