How can I add a condition inside a php array?

前端 未结 8 948
小鲜肉
小鲜肉 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:05

    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.

提交回复
热议问题