PHP is assigned to an array only if it exists

I am currently using this code to assign a variable to an array only if it does not contain a null reference. Is their any keyboard shortcut / alternative method?

if (!is_null($foo)) {
    $var['foo'] = $foo;
}

if (!is_null($bar)) {
    $var['bar'] = $bar;
}

      

+3


source to share


2 answers


Well, you can use the ternary operator as a "shortcut":

is_null($foo) ?: $var['foo'] = $foo;

      

- but I would not recommend that.



This works because it $var['foo'] = $foo

is itself a valid expression - but does it "twist" the whole concept of the operator.


Edit: as others have asked and in the comments, a little more context would be helpful. If you are not asking for this out of pure curiosity, but, for example, because you need to do it for several variables, then all inserting them into an array and then using them array_filter

to "throw" the null

values โ€‹โ€‹afterwards can be more direct ...

+3


source


$a = 'var';
For ($x = 1; $x < 3; $x++){
  if (!is_null(${$a.$i})) {
    $combinations[$a.$i] = ${$a.$i};
  }
}

      



0


source







All Articles