12

What's a nicer way to do the following, that doesn't call f() twice?

$x = f() ? f() : 'default';

5 Answers 5

30

In PHP 5.3, you can also do:

  $a = f() ?: 'default';

See the manual on ?: operator.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 since I haven't seen that used in any of my books that cover PHP 5.3. Very good to know.
8

This seems to work fine:

$x = f() or $x = 'default';

Comments

2
function f()
{
  // conditions 
  return $if_something ? $if_something : 'default';
}

$x = f();

1 Comment

Ah, good answer. I meant for f() to be something we don't have control over and in fact the way this came up for me it wasn't a function at all but $_REQUEST['foo'] so it wasn't an efficiency issue so much as a typing issue.
1
$x = ($result = foo()) ? $result : 'default';

test

1 Comment

This works, but it looks like it can be done more cleanly, with no temp variable.
0

You could save it to a variable. Testcase:

function test() {
        echo 'here';
        return 1;
}

$t = test();
$x = $t ? $t : 0;
echo $x;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.