How can I conditionally add 'b' => 'xyz'
in the array below, in the array() statement?
$arr = array('a' => abc)
The ternary operator doesn't let me do it
To conditionally add a property to an object, we can make use of the && operator. In the example above, in the first property definition on obj , the first expression ( trueCondition ) is true/truthy, so the second expression is returned, and then spread into the object.
For example, if condition «a» is an array of Booleans (true or false values), it returns an array with the same index, containing «b» or «c» as appropriate: Variable X := -2 .. 2. If X > 0 THEN 'Positive' ELSE IF X < 0 THEN 'Negative' ELSE 'Zero' →
The push() method is used to add one or multiple elements to the end of an array. It returns the new length of the array formed. An object can be inserted by passing the object as a parameter to this method. The object is hence added to the end of the array.
When you want to add an element to the end of your array, use push(). If you need to add an element to the beginning of your array, try unshift(). And you can add arrays together using concat().
$a = array('a' => 'abc') + ($condition ? array('b' => 'xyz') : array());
You need two steps:
$arr = array('a' => 'abc');
if(condition) {
$arr['b'] = 'xyz';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With