Search code examples
phploopsfor-looplanguage-construct

ECHO does not work in the third exp of FOR LOOP but PRINT does work?


Why is this valid:

for ($i = 0; $i < 10; print $i++);

and this gives syntax error:

for ($i = 0; $i < 10; echo $i++);

What's the difference? Both are language constructs. Is there a rule what is valid and what not?


Solution

  • You are right, both echo and print are language constructs, however print behaves more like a function than you realize. Internally, print is treated like a function by PHP, as it always returns a value (int 1).

    It is because of this crucial difference, that the PHP interpreter allows for calling this special language construct in your for loop - because it treats print as a function, and as such, it can be used in contexts where normally you would use functions. Consider the following code

    <?php (1 > 0) ? print 'true' : print 'false'; ?>
    

    The code above will work, and it will print 'true'. However, consider the following:

    <?php (1 > 0) ? echo 'true' : echo 'false'; ?>
    <?php (1 > 0) ? return 'true' : yield 'false'; ?>
    <?php (1 > 0) ? continue : break; ?>
    

    None of these examples are valid, and will throw a fatal parse error warning. It is because language constructs are treated in a somewhat obscure way (especially print, which is so special that it works unlike all other constructs), in that they behave like functions in some cases, but in others they are very much different.

    Consider the following:

    <?php
    
        function _echo($a)
        {
            echo $a;
        }
    
        (1 > 0) ? _echo('true') : _echo('false');
    
    ?>
    

    This code will work, because we no longer make use of the echo language construct directly, but instead we have created a wrapper function for it. This function will be executed, and PHP no longer cares what are the contents of that function, or what language constructs we use in there.

    Generally, language constructs cannot be used in the context of my second example, or in the context of your for loop. This type of syntax is only valid for functions and methods (which is why print works and echo does not).