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?
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.
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.
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.
In JavaScript, function parameters default to undefined . However, it's often useful to set a different default value.
As of PHP 5.3 you can use the ternary operator while omitting the middle argument:
$x = $x ?: 'default';
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';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With