tags:

views:

227

answers:

6
//In PHP,
$a ? $b : echo $c  //does not work but 
$a ? $b : print $c //works

Is there a reason for this?

BTW,is not a keyword in PHP?

A: 

return value. if you wrote

  $x = $a?$b:echo $c;

what value would $x get on $a being false?

print always returns 1. echo doesn't return anything.

SF.
But I don't have the `$x =` part .Also I tried a function that doesn't have a return value,still works.
PHP functions that do not explicitly return a value will be 'void', that is, they return 'null'. echo, not being a function but a language construct, doesn't return even that. As for lack of $x = ..., PHP is an interpreter. It first calculates the value of the ?: expression, and only then decides whether to discard it or pass it.
SF.
Could whoever modded my answer down explain what is wrong about it?
SF.
+1  A: 

echo does not have a return value, print does!

 void echo  ( string $arg1  [, string $...  ] )

 int print  ( string $arg  )

from php.net

This matters in this case since the ternary operator expects expressions

(expr1) ? (expr2) : (expr3)

echo "something" cannot be classified as an expression.

not is not a PHP keyword.

Wesho
See my comment under @SF
-1 It's not the reason!
Petr Peller
A: 

there is no not keyword in PHP

Pentium10
+2  A: 

echo is not a function, it's language construct. It does not return anything. Another void functions always "return" NULL. It's why the compiler throws error unexpected T_ECHO.

printf, however, is a function and always returns 1.

For example this will work:

function echo2($e)
{
    echo($e);
}

$a ? $b : echo2('foo');
Petr Peller
Actually, print is a language construct too, but it behaves like a function.
SF.
there is no such thing as "language construct"
stereofrog
@stereofrog: http://tinyurl.com/yhd5pw6
Jacco
http://tinyurl.com/ydswsxt
stereofrog
@stereofrog: so official documentation of PHP (first result in the search) is not an authoritative source on information about whether PHP contains such a thing as "language constructs"?
SF.
A: 

Is it because echo is a language construct and print is a function?

majelbstoat
A: 

In c-alike languages there is a difference between statements (like "if", "while" etc) and operators (like +, -, casts etc). Unlike operators, statements cannot be used in expressions, for example, "10 + (if(1) 3 else 4)" is invalid. In php, "echo" is a statement, and "print" is an operator (don't ask). That's why $a = 10 + print 20 is possible, but not $a = 10 + echo 20

stereofrog