3

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

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

if (!is_null($bar)) {
    $var['bar'] = $bar;
}
6
  • 1
    What is wrong with it? It is perfectly clear what the code does; what would be the point of a shortcut/alternative? Commented Jul 25, 2015 at 2:18
  • do you want it to look shorter? you can use ternary operators then. Commented Jul 25, 2015 at 2:19
  • @SverriM.Olsen nothing wrong with it, I was just expecting short assignment logic. :) Commented Jul 25, 2015 at 2:44
  • @BurningCrystals Ternary operators still expect something to be assigned to the index/variable, for eg. in my case if $var2 is null then $combinations['var2'] must not exist! Commented Jul 25, 2015 at 2:45
  • Do you need to do this with a bunch of variables in a row? Is that why you want to shorten it, or is this more of a general question? Anyway, if you do need to do it with multiple variables, you could loop over the variable names and use variable variables Commented Jul 25, 2015 at 3:12

2 Answers 2

3

Well you could use the ternary operator as a “shortcut”:

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

– but I would not really recommend this.

It works because $var['foo'] = $foo in itself is a valid expression – but is it kinda “perverting” the whole concept of the operator a bit.


Edit: As other have asked in comments as well, a little more context would be helpful. If you are not asking this out of pure curiosity, but for example because you have to do this for multiple variables – then putting them all into the array in any case, and then using array_filter to “throw away” the null values afterwards might be more straight forward …

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.