"a first item", if(True){ "conditionalItem" => "-6ren">
gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-28 23:45:16 25 4
gpt4 key购买 nike

这是数组

$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 ')'

最佳答案

很遗憾,这根本不可能。

如果有该项目但具有 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";

关于php - 如何在 php 数组中添加条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5693754/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com