Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Ternary statement within Associative Array to set both key & value?

I've been searching and testing for some time and just can't find if what I am trying to accomplish is possible the way I'm going about it.

I would like to add a key/value pair to an array, when defining the array, based on an ternary statement.

Array(
    'Item 1' => 'Some value',
    (FALSE)? NULL : 'Item 2' => 'Another Value'
)

My expected/wanted behavior is for the result to then be:

Array (
  [Item 1] => Some value
  [Item 2] => Another Value
)

And when the statement is True:

Array(
    'Item 1' => 'Some value',
    (TRUE)? NULL : 'Item 2' => 'Another Value'
)

Yield:

Array (
  [Item 1] => Some value
)

But instead I get:

Array (
  [Item 1] => Some value
  [] => Another Value
)

Which causes problems since A) I don't want this second element to exist in the first place and B) The False condition value is assigned to the True conditions value (in this case NULL, which sets the key to NULL [])

This is very peculiar. Is my only option to have a standard if(){} statement and Pop the element if the condition is false (by using !) into the array?

Note: Having a null value for Item 2 is not acceptable, rather if the initial condition is true, no element should exist at all.

Any help would be greatly appreciated!

like image 534
thatnetworkguy Avatar asked Feb 07 '15 04:02

thatnetworkguy


1 Answers

All you're doing with that ternary operator is to decide on the key name. The element is going to be put into the array no matter what, it's right there in the array literal declaration.

The best you could do with an inline expression is something like this:

['foo' => 'bar'] + (true ? [] : ['baz' => 42])

Practically, you should probably better write:

$arr = ['foo' => 'bar'];
if (true) {
    $arr['baz'] = 42;
}

Writing more compact code is not always the best goal to have, it needs to be readable and understandable first of all.

like image 64
deceze Avatar answered Nov 05 '22 20:11

deceze