如何在 php 数组中添加条件? [英] How can I add a condition inside a php array?
本文介绍了如何在 php 数组中添加条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是数组
$anArray = 数组(第一项" =>第一项",如果是真的){条件项目" =>它可能会根据条件出现",}最后一项" =>最后一项");
但是我得到了 PHP Parse 错误,为什么我可以在数组中添加一个条件,发生了什么??:
<块引用>PHP 解析错误:语法错误,意外的 T_IF,期待 ')'
解决方案
不幸的是,这根本不可能.
如果有项目但值为 NULL 没有问题,请使用:
$anArray = 数组(第一项" =>第一项",条件项目" =>$条件?它可能会根据条件出现":NULL,最后一项" =>最后一项");
否则你必须这样做:
$anArray = 数组(第一项" =>第一项",最后一项" =>最后一项");如果($条件){$anArray['conditionalItem'] = "它可能会根据条件出现";}
如果顺序重要,那就更丑了:
$anArray = array("theFirstItem" => "a first item");如果($条件){$anArray['conditionalItem'] = "它可能会根据条件出现";}$anArray['theLastItem'] = "最后一项";
不过,您可以使这更具可读性:
$anArray = array();$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屋!
查看全文