如何在php数组中添加条件?

2022-08-30 12:54:44

这是数组

$anArray = array(
   "theFirstItem" => "a first item",
   if(True){
     "conditionalItem" => "it may appear base on the condition",
   }
   "theLastItem"  => "the last item"

);

但是我得到PHP Parse错误,为什么我可以在数组中添加一个条件,会发生什么??:

PHP Parse error:  syntax error, unexpected T_IF, expecting ')'

答案 1

不幸的是,这根本不可能。

如果可以有该项目但具有 NULL 值,请使用:

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

否则,您必须像这样操作:

$anArray = array(
   "theFirstItem" => "a first item",
   "theLastItem"  => "the last item"
);

if($condition) {
   $anArray['conditionalItem'] = "it may appear base on the condition";
}

如果顺序很重要,那就更丑陋了:

$anArray = array("theFirstItem" => "a first item");
if($condition) {
   $anArray['conditionalItem'] = "it may appear base on the condition";
}
$anArray['theLastItem'] = "the last item";

不过,您可以使本文更具可读性:

$anArray = array();
$anArray['theFirstItem'] = "a first item";
if($condition) {
   $anArray['conditionalItem'] = "it may appear base on the condition";
}
$anArray['theLastItem'] = "the last item";

答案 2

如果要创建纯关联数组,并且键的顺序无关紧要,则始终可以使用三元运算符语法有条件地命名键。

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

这样,如果满足条件,则密钥与数据一起存在。如果不是,它只是一个具有空字符串值的空白键。但是,鉴于已经列出了其他答案,可能有更好的选择来满足您的需求。这并不是完全干净,但是如果您正在处理一个具有大型数组的项目,则可能比从数组中分离然后添加更容易;特别是如果数组是多维的。