Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign if variable is set

Tags:

variables

php

In PHP I find myself writing code like this frequently:

$a = isset($the->very->long->variable[$index])             ? $the->very->long->variable[$index]             : null; 

Is there a simpler way to do this? Preferably one that doesn't require me to write $the->very->long->variable[$index] twice.

like image 661
oz1cz Avatar asked Nov 29 '12 13:11

oz1cz


People also ask

How do you assign a default value to a variable in UNIX?

Or to assign default to VARIABLE at the same time: FOO="${VARIABLE:=default}" # If variable not set or null, set it to default.

How do you assign a value to a variable in a shell script using IF statement?

This will work: x = $(if [ 2 = 2 ]; then echo equal; else echo "not equal; fi) . See gnu.org/software/bash/manual/bash.html#Conditional-Constructs . Note that case matters -- If and if are not the same. if you want to echo it in one line.

What is set variable?

Description. The Set-Variable cmdlet assigns a value to a specified variable or changes the current value. If the variable does not exist, the cmdlet creates it.


1 Answers

An update, because PHP 7 is now out and is a game-changer on this point ; the previous answers are about PHP 5.

PHP 7 solves this issue. Because you are true at saying that it is frequent to write this in PHP, and that's absolutely not elegant.

In PHP 7 comes the Null Coalesce Operator (RFC), which is a perfect shorthand for the isset ternary condition.

Its goal is to replace this type of condition:

$var = isset($dict['optional']) ? $dict['optional'] : 'fallback'; 

By that:

$var = $dict['optional'] ?? 'fallback'; 

Even better, the null coalesce operators are chainable:

$x = null; # $y = null; (undefined) $z = 'fallback';  # PHP 7 echo $x ?? $y ?? $z   #=> "fallback"  # PHP 5 echo isset($x) ? $x : (isset($y) ? $y : $z) 

The null coalesce operator acts exactly like isset() : the subject variable's value is taken if:

  • The variable is defined (it exists)
  • The variable is not null

Just a note for PHP beginners: if you use the ternary condition but you know that the subject variable is necessarily defined (but you want a fallback for falsy values), there's the Elvis operator:

$var = $dict['optional'] ?: 'fallback'; 

With the Elvis operator, if $dict['optional'] is an invalid offset or $dict is undefined, you'll get a E_NOTICE warning (PHP 5 & 7). That's why, in PHP 5, people are using the hideous isset a ? a : b form when they're not sure about the input.

like image 66
Morgan Touverey Quilling Avatar answered Oct 02 '22 22:10

Morgan Touverey Quilling