'How can I add a condition inside a php array?

Here is the array

$anArray = array(
   "theFirstItem" => "a first item",
   if(True){
     "conditionalItem" => "it may appear base on the condition",
   }
   "theLastItem"  => "the last item"

);

But I get the PHP Parse error, why I can add a condition inside the array, what's happen??:

PHP Parse error:  syntax error, unexpected T_IF, expecting ')'


Solution 1:[1]

If you are making a purely associative array, and order of keys does not matter, you can always conditionally name the key using the ternary operator syntax.

$anArray = array(
    "theFirstItem" => "a first item",
    (true ? "conditionalItem" : "") => (true ? "it may appear base on the condition" : ""),
    "theLastItem" => "the last item"
);

This way, if the condition is met, the key exists with the data. If not, it's just a blank key with an empty string value. However, given the great list of other answers already, there may be a better option to fit your needs. This isn't exactly clean, but if you're working on a project that has large arrays it may be easier than breaking out of the array and then adding afterwards; especially if the array is multidimensional.

Solution 2:[2]

Your can do it like this:

$anArray = array(1 => 'first');
if (true) $anArray['cond'] = 'true';
$anArray['last'] = 'last';

However, what you want is not possible.

Solution 3:[3]

There's not any magic to help here. The best you can do is this:

$anArray = array("theFirstItem" => "a first item");
if (true) {
    $anArray["conditionalItem"] = "it may appear base on the condition";
}
$anArray["theLastItem"]  = "the last item";

If you don't care specifically about the order of the items, it gets a little more bearable:

$anArray = array(
    "theFirstItem" => "a first item",
    "theLastItem"  => "the last item"
);
if (true) {
    $anArray["conditionalItem"] = "it may appear base on the condition";
}

Or, if the order does matter and the conditional items are more than a couple, you can do this which could be considered more readable:

$anArray = array(
    "theFirstItem" => "a first item",
    "conditionalItem" => "it may appear base on the condition",
    "theLastItem"  => "the last item",
);

if (!true) {
    unset($anArray["conditionalItem"]);
}

// Unset any other conditional items here

Solution 4:[4]

Try this if you have associative array with different keys:

$someArray = [
    "theFirstItem" => "a first item",
] + 
$condition 
    ? [
        "conditionalItem" => "it may appear base on the condition"
      ] 
    : [ /* empty array if false */
] + 
[
    "theLastItem" => "the last item",
];

or this if array not associative

$someArray = array_merge(
    [
        "a first item",
    ],
    $condition 
        ? [
            "it may appear base on the condition"
          ] 
        : [ /* empty array if false */
    ], 
    [
        "the last item",
    ]
);

Solution 5:[5]

You can assign all values and filter empty keys from the array at once like this:

$anArray = array_filter([
   "theFirstItem" => "a first item",
   "conditionalItem" => $condition ? "it may appear base on the condition" : NULL,
   "theLastItem"  => "the last item"
]);

This allows you avoid the extra conditional after the fact, maintain key order, and imo it's fairly readable. The only caveat here is that if you have other falsy values (0, false, "", array()) they will also be removed. In that case you may wish to add a callback to explicitly check for NULL. In the following case theLastItem won't get unintentionally filtered:

$anArray = array_filter([
    "theFirstItem" => "a first item",
    "conditionalItem" => $condition ? "it may appear base on the condition" : NULL,
    "theLastItem"  => false,
], function($v) { return $v !== NULL; });

Solution 6:[6]

You can do it like this:

$anArray = array(
    "theFirstItem" => "a first item",
    (true ? "conditionalItem" : "EMPTY") => (true ? "it may appear base on the condition" : "EMPTY"),
    "theLastItem" => "the last item"
);

unset the EMPTY array item if the condition is false

unset($anArray['EMPTY']);

Solution 7:[7]

Its pretty simple. Create array with essential elements. Then add conditional elements to the array. Now add other elements if required.

$anArray = array(
    "theFirstItem" => "a first item"
);

if(True){
    $anArray+=array("conditionalItem" => "it may appear base on the condition");
}

$more=array(
    "theLastItem"  => "the last item"
); 

$anArray+=$more;

You modify this code to make it even more shorter,, i have just given elaborated code to make it self explantory. No NULL element, no empty string, put you item anywhere you want, no hassel.

Solution 8:[8]

You can use array_merge

$result = array_merge(
    ['apple' => 'two'],
    (true ? ['banana' => 'four'] : []),
    (false ? ['strawberry' => 'ten'] : [])
);

print_r($result);

// Output:
/* 
Array
(
    [apple] => 'two'
    [banana] => 'four'
) 
*/

Drawback of array_merge: Values in an array with numeric keys will be renumbered with incrementing keys starting from zero in the result array. You can use the union operator instead to maintain the original numeric keys

Or by using Array Union Operator

$result = ['apple' => 'two'] + (true ? ['banana' => 'four'] : []) + (false ? ['strawberry' => 'ten'] : []);

print_r($result);

// Output:
/* 
Array
(
    [apple] => 'two'
    [banana] => 'four'
) 
*/

Note: When using the union operator, remember that for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Adam Kelso
Solution 2 kojow7
Solution 3 Jon
Solution 4 Tony Axo
Solution 5
Solution 6 Asim Ansari
Solution 7 Atai Rabby
Solution 8 mickmackusa