How can I add a condition inside a php array?

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

    You can assign all values and filter empty keys from the array at once like this:

    $anArray = array_filter([
       "theFirstItem" => "a first item",
       "conditionalItem" => $condition ? "it may appear base on the condition" : NULL,
       "theLastItem"  => "the last item"
    ]);
    

    This allows you avoid the extra conditional after the fact, maintain key order, and imo it's fairly readable. The only caveat here is that if you have other falsy values (0, false, "", array()) they will also be removed. In that case you may wish to add a callback to explicitly check for NULL. In the following case theLastItem won't get unintentionally filtered:

    $anArray = array_filter([
        "theFirstItem" => "a first item",
        "conditionalItem" => $condition ? "it may appear base on the condition" : NULL,
        "theLastItem"  => false,
    ], function($v) { return $v !== NULL; });
    

提交回复
热议问题