Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP assignment with a default value

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

$x = f() ? f() : 'default';
like image 475
dreeves Avatar asked Jan 28 '11 19:01

dreeves


People also ask

How to set default value in PHP function?

Setting Default Values for Function parameterPHP allows us to set default argument values for function parameters. If we do not pass any argument for a parameter with default value then PHP will use the default set value for this parameter in the function call. Example: PHP.

What does& in PHP?

An ampersand just before the function name will return a reference to the variable instead of returning its value. Returning by reference is useful when you want to use a function to find to which variable a reference should be bound.

How to assign in PHP?

The PHP assignment operators are used with numeric values to write a value to a variable. The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of the assignment expression on the right.


2 Answers

In PHP 5.3, you can also do:

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

See the manual on ?: operator.

like image 53
StasM Avatar answered Oct 16 '22 01:10

StasM


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

$x = f();
like image 28
ajreal Avatar answered Oct 16 '22 03:10

ajreal