How can I add a condition inside a php array?

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

    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",
        ]
    );
    

提交回复
热议问题