0
<?

function foo($return = false) {
    $x = '12345';

    $return ?
    return $x : // here it fails
    echo $x;
}

echo foo(true);

?>

It says "Parse error: syntax error, unexpected 'return' (T_RETURN) in..."

Why!? :)

jotik
  • 17,044
  • 13
  • 58
  • 123
daryqsyro
  • 157
  • 2
  • 9

2 Answers2

2

You can't use inline ifs in this way. They are normally used like this:

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

Your code should be like this:

<?

function foo($return = false) {
    $x = '12345';

    if($return)
    {
        return $x
    }
    else
    {
        echo $x;
    }
}

echo foo(true);

?>

(more confusing for some), you don't need to add the else statement, as if the if statement is satisfied, it will return a value, thus exiting the function, which means if the if statement is not satisfied, it will go to the echo anyway:

<?

function foo($return = false) {
    $x = '12345';

    if($return)
    {
        return $x
    }
    echo $x;
}

echo foo(true);

?>
user3476093
  • 704
  • 2
  • 6
  • 11
  • Inline ifs are called ternary operators btw. You also don't need the else part of the if, you can just do `if($return) { return $x; } echo $x;` – Styphon Jun 14 '15 at 10:48
  • Can you please explain what is the difference? Regular if works great but why inline if doesn't? – daryqsyro Jun 14 '15 at 10:49
  • @daryqsyro because a [ternary operator](http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary) is not the same as an if statement. You use ternary operators to return one value or another. Using the return from function in one breaks the ternary operator. – Styphon Jun 14 '15 at 10:51
  • @Styphon - I was contemplating whether to add `if($return) { return $x; } echo $x;` but I thought it would be less confusing for some people if I wrote it like I did. – user3476093 Jun 14 '15 at 10:56
  • @user3476093 Fair enough. – Styphon Jun 14 '15 at 10:57
  • @Styphon - I have now added the function without an `else` statement aswell – user3476093 Jun 14 '15 at 10:58
0

You can use the print function instead of echo:

<?php
function foo($return = false) {
    $x = '12345';

    return $return ? $x : print($x);
}

$x = foo(true);

More elegant is Styphons way from the comments:

if ($return) { return $x; } echo $x;
Markus Kottländer
  • 8,228
  • 4
  • 37
  • 61