PHP ternary operator in associative array to set both key and value?

I searched and tested for a while and just can’t find that what I am trying to accomplish is perhaps how I am doing it.

I would like to add a key / value pair to an array when defining an array based on a three-dimensional statement.

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

Expected / desired behavior for the result:

 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' ) 

Output:

 Array ( [Item 1] => Some value ) 

But instead, I get:

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

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

It is very strange. Is my only option is to have the standard if () {} operator and call the element if this condition is false (using!) In an array?

Note. The presence of a null value for element 2 is unacceptable, but if the initial condition is true, no element should exist at all.

Any help would be greatly appreciated!

+6
source share
2 answers

All you do with this ternary operator is defining a key name. The element will be placed in the array, regardless of whether it is directly in the declaration of the array literal.

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

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

In practice, you'd better write:

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

Writing more compact code is not always the best goal, it should be readable and understandable in the first place.

+7
source

This would be possible only if the approval was withdrawn.

For example, you take a value for a key that PHP cannot process (for example, an array), and whenever you do not want to add an entry, you use that key.

The principle is actually similar to what you drew with the NULL value:

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

The disadvantage of this is that the code is bulky, fuzzy to read and gives warnings:

Warning: invalid offset type

Therefore, I am adding this answer more for completeness.

Full example ( online demo ):

 <?php /** * PHP Ternary statement within Associative Array to set both key & value? * @link http://stackoverflow.com/a/29327671/367456 */ var_dump( Array( 'Item 1' => 'Some value', TRUE ? array() : 'Item 2' => 'Another Value', FALSE ? array() : 'Item 3' => 'Just Another Value', ) ); 
0
source

Source: https://habr.com/ru/post/982127/


All Articles