PHP - what's wrong with this piece of code? -


<?  function foo($return = false) {     $x = '12345';      $return ?     return $x : // here fails     echo $x; }  echo foo(true);  ?> 

it says "parse error: syntax error, unexpected 'return' (t_return) in..."

why!? :)

you can't use inline ifs in way. used this:

echo ($return ? x : "false");

your code should this:

<?  function foo($return = false) {     $x = '12345';      if($return)     {         return $x     }     else     {         echo $x;     } }  echo foo(true);  ?> 

(more confusing some), don't need add else statement, if if statement satisfied, return value, exiting function, means if if statement not satisfied, go echo anyway:

<?  function foo($return = false) {     $x = '12345';      if($return)     {         return $x     }     echo $x; }  echo foo(true);  ?> 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -