我怎么能一个PHP数组中添加一个条件? [英] How can I add a condition inside a php array?

查看:157
本文介绍了我怎么能一个PHP数组中添加一个条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是数组

  $ anArray =阵列(
   theFirstItem=> 第一项,
   如果属实){
     conditionalItem=> 它可能会出现在条件基地,
   }
   theLastItem=> 最后一个项目);

但我得到的PHP解析错误,为什么我可以添加数组中的条件,有什么发生?


  PHP解析错误:语法错误,意想不到的T_IF,预计')'



解决方案

不幸的是这是不可能的。

如果有这个项目,但有一个NULL值是确定的,使用:

  $ anArray =阵列(
   theFirstItem=> 第一项,
   conditionalItem=> $条件? 它可能会在条件出现基地:NULL,
   theLastItem=> 最后一个项目
);

另外,你必须做这样的:

  $ anArray =阵列(
   theFirstItem=> 第一项,
   theLastItem=> 最后一个项目
);如果($条件){
   $ anArray ['conditionalItem'] =它可能会出现在条件基地;
}

如果订单事宜,这将是丑陋连:

  $ anArray =阵列(theFirstItem=>中第一项);
如果($条件){
   $ anArray ['conditionalItem'] =它可能会出现在条件基地;
}
$ anArray ['theLastItem'] =最后一个项目;

您可以使这一点更可读,但:

  $ anArray =阵列();
$ anArray ['theFirstItem'] =第一项;
如果($条件){
   $ anArray ['conditionalItem'] =它可能会出现在条件基地;
}
$ anArray ['theLastItem'] =最后一个项目;

Here is the array

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

);

But I get the PHP Parse error, why I can add a condition inside the array, what's happen??:

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

解决方案

Unfortunately that's not possible at all.

If having the item but with a NULL value is ok, use this:

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

Otherwise you have to do it like that:

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

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

If the order matters, it'll be even uglier:

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

You could make this a little bit more readable though:

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

这篇关于我怎么能一个PHP数组中添加一个条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆