Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conditionally adding a element in a array

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

like image 374
user815340 Avatar asked Jun 25 '11 13:06

user815340


People also ask

How do you conditionally add an object to an array?

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.

How do you write a condition in an array?

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

How do you add an array to an OBJ?

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.

Which array Funcitons can be used to add elements in an 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().


2 Answers

$a = array('a' => 'abc') + ($condition ? array('b' => 'xyz') : array());
like image 116
Andreas Jansson Avatar answered Oct 30 '22 02:10

Andreas Jansson


You need two steps:

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

if(condition) {
    $arr['b'] = 'xyz';
}
like image 32
Felix Kling Avatar answered Oct 30 '22 04:10

Felix Kling