这是数组
$anArray = array(
"theFirstItem" => "a first item",
if(True){
"conditionalItem" => "it may appear base on the condition",
}
"theLastItem" => "the last item"
);
但是我得到了PHP解析错误,为什么我可以在数组中添加一个条件,发生了什么??:
Parse错误:语法错误,意外的T_IF,应为')'
发布于 2011-04-17 21:23:14
不幸的是,这是完全不可能的。
如果拥有该项目但值为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";
发布于 2014-04-30 04:23:55
如果您要创建一个纯粹的关联数组,并且键的顺序并不重要,则始终可以使用三元运算符语法有条件地命名键。
$anArray = array(
"theFirstItem" => "a first item",
(true ? "conditionalItem" : "") => (true ? "it may appear base on the condition" : ""),
"theLastItem" => "the last item"
);
这样,如果满足条件,密钥将与数据一起存在。如果不是,它只是一个带有空字符串值的空键。然而,考虑到已经有一大堆其他答案,也许还有更好的选择来满足你的需求。这并不是很干净,但如果您正在处理一个包含大型数组的项目,则可能比打破数组然后添加更容易;特别是在数组是多维的情况下。
发布于 2011-04-17 21:23:58
你可以这样做:
$anArray = array(1 => 'first');
if (true) $anArray['cond'] = 'true';
$anArray['last'] = 'last';
然而,你想要的是不可能的。
https://stackoverflow.com/questions/5693754
复制相似问题