If I use print
in this code:
<?php
for($i = 1; $i <= 3; print $i . "\n") {
$i++;
}
?>
I see as output this:
2
3
4
But when I use echo
the code doesn't work:
<?php
for($i = 1; $i <= 3; echo $i . "\n") {
$i++;
}
?>
I see this error:
PHP Parse error: syntax error, unexpected 'echo' (T_ECHO), expecting ')' in /media/datos/xampp/htdocs/temp/1.php on line 3
My question is:
- Why can I use
print
as a third expression in afor
loop, but cannot when usingecho
and why do they behave differently from each other?
References:
print
returns a value; whileecho
doesn't return any value.... and an expression requires a value – Elongationprint is not actually a real function (it is a language construct)
– Armed$i++
does give a value.... as do all operatorsAn operator is something that takes one or more values (or expressions, in programming jargon) __and yields another value (so that the construction itself becomes an expression)__.
– Elongationfunction a() { //just test; } for($i = 1; $i <= 3; a()) { $i++; }
and it works and don't return any value – Hygienistprint print 'hello';
while this is invalidecho echo 'hello';
for the same reason, echo has not return value – Adellaadellereturn
will return anull
, that's a valid value in PHP,print
returns an integer, which is a valid value..... echo returnsvoid
, which isn't a value – Elongation"\n"
but in your original question you have those numbers listed one of top of each other, as if on new lines.\n
will not give you those hard returns, but rather spaces. This will only appear as new lines if you're writing to a file. Is there a particular reason why you're using"\n"
rather than a space" "
? Is there a new reason for this that you haven't completely shared? Unless those numbers on top like that, was a mistake and you meant to write it as in a single line2 3 4
? – Besmirch<br/>
). That has nothing to do with PHP. Try echoing"\n"
in PHP through a web request, then hit "view source" in your browser. – Viol