Tat*_*tat 25 php arrays syntax
这是阵列
$anArray = array(
"theFirstItem" => "a first item",
if(True){
"conditionalItem" => "it may appear base on the condition",
}
"theLastItem" => "the last item"
);
Run Code Online (Sandbox Code Playgroud)
但是我得到PHP Parse错误,为什么我可以在数组中添加一个条件,会发生什么?:
Run Code Online (Sandbox Code Playgroud)PHP Parse error: syntax error, unexpected T_IF, expecting ')'
Thi*_*ter 38
不幸的是,根本不可能.
如果拥有该项但具有NULL值,则使用此:
$anArray = array(
"theFirstItem" => "a first item",
"conditionalItem" => $condition ? "it may appear base on the condition" : NULL,
"theLastItem" => "the last item"
);
Run Code Online (Sandbox Code Playgroud)
否则你必须这样做:
$anArray = array(
"theFirstItem" => "a first item",
"theLastItem" => "the last item"
);
if($condition) {
$anArray['conditionalItem'] = "it may appear base on the condition";
}
Run Code Online (Sandbox Code Playgroud)
如果订单很重要,那就更加丑陋了:
$anArray = array("theFirstItem" => "a first item");
if($condition) {
$anArray['conditionalItem'] = "it may appear base on the condition";
}
$anArray['theLastItem'] = "the last item";
Run Code Online (Sandbox Code Playgroud)
你可以让它更具可读性:
$anArray = array();
$anArray['theFirstItem'] = "a first item";
if($condition) {
$anArray['conditionalItem'] = "it may appear base on the condition";
}
$anArray['theLastItem'] = "the last item";
Run Code Online (Sandbox Code Playgroud)
小智 5
如果要创建纯关联数组,并且键的顺序无关紧要,则始终可以使用三元运算符语法有条件地命名键。
$anArray = array(
"theFirstItem" => "a first item",
(true ? "conditionalItem" : "") => (true ? "it may appear base on the condition" : ""),
"theLastItem" => "the last item"
);
Run Code Online (Sandbox Code Playgroud)
这样,如果满足条件,则密钥与数据一起存在。如果不是,那只是一个带有空字符串值的空白键。但是,鉴于已经有很多其他答案,可能有更好的选择来满足您的需求。这不是完全干净,但是如果您正在处理具有大型数组的项目,则可能要比打破数组然后再添加要容易。特别是如果数组是多维的。