Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting default values (conditional assignment)

In Ruby you can easily set a default value for a variable

x ||= "default" 

The above statement will set the value of x to "default" if x is nil or false

Is there a similar shortcut in PHP or do I have to use the longer form:

$x = (isset($x))? $x : "default"; 

Are there any easier ways to handle this in PHP?

like image 494
ejunker Avatar asked Oct 02 '08 15:10

ejunker


People also ask

How do you assign default values to variables?

The OR Assignment (||=) Operator The logical OR assignment ( ||= ) operator assigns the new values only if the left operand is falsy. Below is an example of using ||= on a variable holding undefined . Next is an example of assigning a new value on a variable containing an empty string.

Where should set the default values?

Set a default valueIn the Navigation Pane, right-click the form that you want to change, and then click Design View. Right-click the control that you want to change, and then click Properties or press F4. Click the All tab in the property sheet, locate the Default Value property, and then enter your default value.

Can a type have a default value TypeScript?

To set default values for an interface in TypeScript, create an initializer function, which defines the default values for the type and use the spread syntax (...) to override the defaults with user-provided values.

What is the default value of variable in JavaScript?

In JavaScript, function parameters default to undefined . However, it's often useful to set a different default value.


2 Answers

As of PHP 5.3 you can use the ternary operator while omitting the middle argument:

$x = $x ?: 'default'; 
like image 118
igorw Avatar answered Oct 04 '22 10:10

igorw


As of PHP 7.0, you can also use the null coalesce operator

// PHP version < 7.0, using a standard ternary $x = (isset($_GET['y'])) ? $_GET['y'] : 'not set'; // PHP version >= 7.0 $x = $_GET['y'] ?? 'not set'; 
like image 20
Machavity Avatar answered Oct 04 '22 12:10

Machavity