How can I add a condition inside a php array?

前端 未结 8 987
小鲜肉
小鲜肉 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-10 01:27

    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";
    

提交回复
热议问题