首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在php数组中添加条件?

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

Stack Overflow用户
提问于 2011-04-17 21:22:00
回答 8查看 49.9K关注 0票数 33

这是数组

代码语言:javascript
复制
$anArray = array(
   "theFirstItem" => "a first item",
   if(True){
     "conditionalItem" => "it may appear base on the condition",
   }
   "theLastItem"  => "the last item"

);

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

Parse错误:语法错误,意外的T_IF,应为')'

EN

回答 8

Stack Overflow用户

回答已采纳

发布于 2011-04-17 21:23:14

不幸的是,这是完全不可能的。

如果拥有该项目但值为null值,则可以使用以下命令:

代码语言:javascript
复制
$anArray = array(
   "theFirstItem" => "a first item",
   "conditionalItem" => $condition ? "it may appear base on the condition" : NULL,
   "theLastItem"  => "the last item"
);

否则你必须这样做:

代码语言:javascript
复制
$anArray = array(
   "theFirstItem" => "a first item",
   "theLastItem"  => "the last item"
);

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

如果顺序很重要,它将变得更加丑陋:

代码语言:javascript
复制
$anArray = array("theFirstItem" => "a first item");
if($condition) {
   $anArray['conditionalItem'] = "it may appear base on the condition";
}
$anArray['theLastItem'] = "the last item";

不过,您可以让它更具可读性:

代码语言:javascript
复制
$anArray = array();
$anArray['theFirstItem'] = "a first item";
if($condition) {
   $anArray['conditionalItem'] = "it may appear base on the condition";
}
$anArray['theLastItem'] = "the last item";
票数 49
EN

Stack Overflow用户

发布于 2014-04-30 04:23:55

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

代码语言:javascript
复制
$anArray = array(
    "theFirstItem" => "a first item",
    (true ? "conditionalItem" : "") => (true ? "it may appear base on the condition" : ""),
    "theLastItem" => "the last item"
);

这样,如果满足条件,密钥将与数据一起存在。如果不是,它只是一个带有空字符串值的空键。然而,考虑到已经有一大堆其他答案,也许还有更好的选择来满足你的需求。这并不是很干净,但如果您正在处理一个包含大型数组的项目,则可能比打破数组然后添加更容易;特别是在数组是多维的情况下。

票数 6
EN

Stack Overflow用户

发布于 2011-04-17 21:23:58

你可以这样做:

代码语言:javascript
复制
$anArray = array(1 => 'first');
if (true) $anArray['cond'] = 'true';
$anArray['last'] = 'last';

然而,你想要的是不可能的。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5693754

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档