php 如何在php数组中添加条件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5693754/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I add a condition inside a php array?
提问by Tattat
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 错误,为什么我可以在数组中添加一个条件,发生了什么??:
PHP Parse error: syntax error, unexpected T_IF, expecting ')'
PHP Parse error: syntax error, unexpected T_IF, expecting ')'
回答by ThiefMaster
Unfortunately that's not possible at all.
不幸的是,这根本不可能。
If having the item but with a NULL value is ok, use this:
如果有该项目但值为 NULL 没问题,请使用以下命令:
$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";
回答by Adam Kelso
If you are making a purely associative array, and order of keys does not matter, you can always conditionally name the key using the ternary operator syntax.
如果您正在制作一个纯粹的关联数组,并且键的顺序无关紧要,您始终可以使用三元运算符语法有条件地命名键。
$anArray = array(
"theFirstItem" => "a first item",
(true ? "conditionalItem" : "") => (true ? "it may appear base on the condition" : ""),
"theLastItem" => "the last item"
);
This way, if the condition is met, the key exists with the data. If not, it's just a blank key with an empty string value. However, given the great list of other answers already, there may be a better option to fit your needs. This isn't exactly clean, but if you're working on a project that has large arrays it may be easier than breaking out of the array and then adding afterwards; especially if the array is multidimensional.
这样,如果满足条件,则密钥与数据一起存在。如果没有,它只是一个带有空字符串值的空白键。但是,鉴于已经有很多其他答案,可能会有更好的选择来满足您的需求。这并不完全干净,但是如果您正在处理具有大型数组的项目,它可能比打破数组然后添加更容易;特别是如果数组是多维的。
回答by azat
Your can do it like this:
你可以这样做:
$anArray = array(1 => 'first');
if (true) $anArray['cond'] = 'true';
$anArray['last'] = 'last';
However, what you want is not possible.
然而,你想要的却是不可能的。
回答by Jon
There's not any magic to help here. The best you can do is this:
没有任何魔法可以帮助这里。你能做的最好的是:
$anArray = array("theFirstItem" => "a first item");
if (true) {
$anArray["conditionalItem"] = "it may appear base on the condition";
}
$anArray["theLastItem"] = "the last item";
If you don't care specifically about the order of the items, it gets a little more bearable:
如果你不特别关心物品的顺序,它会变得更容易忍受:
$anArray = array(
"theFirstItem" => "a first item",
"theLastItem" => "the last item"
);
if (true) {
$anArray["conditionalItem"] = "it may appear base on the condition";
}
Or, if the order doesmatter and the conditional items are more than a couple, you can do this which could be considered more readable:
或者,如果订单确实很重要并且条件项不止一对,您可以这样做,这可能被认为更具可读性:
$anArray = array(
"theFirstItem" => "a first item",
"conditionalItem" => "it may appear base on the condition",
"theLastItem" => "the last item",
);
if (!true) {
unset($anArray["conditionalItem"]);
}
// Unset any other conditional items here
回答by Tony Axo
Try this if you have associative array with different keys:
如果你有不同键的关联数组,试试这个:
$someArray = [
"theFirstItem" => "a first item",
] +
$condition
? [
"conditionalItem" => "it may appear base on the condition"
]
: [ /* empty array if false */
] +
[
"theLastItem" => "the last item",
];
or this if array not associative
或者如果数组不关联
$someArray = array_merge(
[
"a first item",
],
$condition
? [
"it may appear base on the condition"
]
: [ /* empty array if false */
],
[
"the last item",
]
);
回答by billynoah
You can assign all values and filter empty keys from the array at once like this:
您可以像这样一次分配所有值并从数组中过滤空键:
$anArray = array_filter([
"theFirstItem" => "a first item",
"conditionalItem" => $condition ? "it may appear base on the condition" : NULL,
"theLastItem" => "the last item"
]);
This allows you avoid the extra conditional after the fact, maintain key order, and imo it's fairly readable. The only caveat here is that if you have other falsy values (0, false, "", array()
) they will also be removed. In that case you may wish to add a callback to explicitly check for NULL
. In the following case theLastItem
won't get unintentionally filtered:
这允许您在事后避免额外的条件,维护密钥顺序,并且它具有相当的可读性。这里唯一需要注意的是,如果您有其他虚假值 ( 0, false, "", array()
),它们也将被删除。在这种情况下,您可能希望添加一个回调来显式检查NULL
. 在以下情况下theLastItem
不会被无意过滤:
$anArray = array_filter([
"theFirstItem" => "a first item",
"conditionalItem" => $condition ? "it may appear base on the condition" : NULL,
"theLastItem" => false,
], function($v) { return $v !== NULL; });
回答by Asim Ansari
You can do it like this:
你可以这样做:
$anArray = array(
"theFirstItem" => "a first item",
(true ? "conditionalItem" : "EMPTY") => (true ? "it may appear base on the condition" : "EMPTY"),
"theLastItem" => "the last item"
);
unset the EMPTY array item if the condition is false
如果条件为假,则取消设置 EMPTY 数组项
unset($anArray['EMPTY']);
回答by Atai Rabby
Its pretty simple. Create array with essential elements. Then add conditional elements to the array. Now add other elements if required.
它很简单。创建包含基本元素的数组。然后将条件元素添加到数组中。如果需要,现在添加其他元素。
$anArray = array(
"theFirstItem" => "a first item"
);
if(True){
$anArray+=array("conditionalItem" => "it may appear base on the condition");
}
$more=array(
"theLastItem" => "the last item"
);
$anArray+=$more;
You modify this code to make it even more shorter,, i have just given elaborated code to make it self explantory. No NULL element, no empty string, put you item anywhere you want, no hassel.
您修改此代码以使其更短,我刚刚给出了详细的代码以使其自我解释。没有 NULL 元素,没有空字符串,把你的项目放在任何你想要的地方,没有麻烦。