Here is the array
$anArray = array(
\"theFirstItem\" => \"a first item\",
if(True){
\"conditionalItem\" => \"it may appear base on the condi
Unfortunately that's not possible at all.
If having the item but with a NULL value is ok, use this:
$anArray = array(
"theFirstItem" => "a first item",
"conditionalItem" => $condition ? "it may appear base on the condition" : NULL,
"theLastItem" => "the last item"
);
Otherwise you have to do it like that:
$anArray = array(
"theFirstItem" => "a first item",
"theLastItem" => "the last item"
);
if($condition) {
$anArray['conditionalItem'] = "it may appear base on the condition";
}
If the order matters, it'll be even uglier:
$anArray = array("theFirstItem" => "a first item");
if($condition) {
$anArray['conditionalItem'] = "it may appear base on the condition";
}
$anArray['theLastItem'] = "the last item";
You could make this a little bit more readable though:
$anArray = array();
$anArray['theFirstItem'] = "a first item";
if($condition) {
$anArray['conditionalItem'] = "it may appear base on the condition";
}
$anArray['theLastItem'] = "the last item";
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