Conditionally adding an element to an array

How can I conditionally add 'b' => 'xyz' to the array below in the array () expression?

$arr = array('a' => abc)

The ternary operator does not allow me to do this

+6
source share
6 answers
 $a = array('a' => 'abc') + ($condition ? array('b' => 'xyz') : array()); 
+4
source

You need to complete two steps:

 $arr = array('a' => 'abc'); if(condition) { $arr['b'] = 'xyz'; } 
+4
source
 $arr = array('a' => 'abc'); if ($condition_required_for_b_to_be_put_in_the_array) { $arr['b'] = 'xyz'; } 

If you really want to use the ternary operator:

 $arr = array('a' => 'abc', $condition ? 'b' : '' => $condition ? 'xyz' : ''); $arr = array_filter($arr); 
+2
source

Not sure what you are asking; why not

 if (condition) { $arr['b'] = 'xyz'; } 
+1
source

This is an old question, but you can accomplish this with array_merge:

 array_merge(['foo' => 'bar'], $condition ? ['baz' => 'boo' ] : []); 
+1
source

Ternar means three members. You must have a condition, a true part and a false part. It replaces the if condition, then the true else part is false. You cannot leave the third part. In 5.3 there is a shortcut that allows you to exclude the true part if the condition can be used also as the true part, but it still has three conditions.

0
source

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


All Articles