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

时间:2022-06-01 14:09:58

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

6 个解决方案

#1


34  

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";

#2


4  

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.

这样,如果满足条件,则密钥与数据一起存在。如果没有,它只是一个空字符串值的空键。但是,鉴于已有其他答案的清单,可能有更好的选择来满足您的需求。这不是很干净,但是如果你正在处理一个有大型数组的项目,那么它可能比打破数组然后再添加更容易;特别是如果数组是多维的。

#3


4  

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.

但是,你想要的是不可能的。

#4


1  

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 does matter 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

#5


1  

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",
    ]
);

#6


0  

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; });

#1


34  

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";

#2


4  

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.

这样,如果满足条件,则密钥与数据一起存在。如果没有,它只是一个空字符串值的空键。但是,鉴于已有其他答案的清单,可能有更好的选择来满足您的需求。这不是很干净,但是如果你正在处理一个有大型数组的项目,那么它可能比打破数组然后再添加更容易;特别是如果数组是多维的。

#3


4  

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.

但是,你想要的是不可能的。

#4


1  

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 does matter 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

#5


1  

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",
    ]
);

#6


0  

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; });