How can I add a condition inside a php array?

前端 未结 8 985
小鲜肉
小鲜肉 2020-12-10 00:49

Here is the array

$anArray = array(
   \"theFirstItem\" => \"a first item\",
   if(True){
     \"conditionalItem\" => \"it may appear base on the condi         


        
8条回答
  •  无人及你
    2020-12-10 01:08

    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']);
    

提交回复
热议问题