Как добавить условие внутри массива php?
Вот массив
$anArray = array(
"theFirstItem" => "a first item",
if(True){
"conditionalItem" => "it may appear base on the condition",
}
"theLastItem" => "the last item"
);
Но я получаю ошибку PHP Parse, почему я могу добавить условие внутри массива, что происходит?:
PHP Parse error: syntax error, unexpected T_IF, expecting ')'
Ответы
Ответ 1
К сожалению, это невозможно вообще.
Если элемент, но с нулевым значением, в порядке, используйте это:
$anArray = array(
"theFirstItem" => "a first item",
"conditionalItem" => $condition ? "it may appear base on the condition" : NULL,
"theLastItem" => "the last item"
);
В противном случае вы должны сделать это следующим образом:
$anArray = array(
"theFirstItem" => "a first item",
"theLastItem" => "the last item"
);
if($condition) {
$anArray['conditionalItem'] = "it may appear base on the condition";
}
Если порядок имеет значение, он будет еще более уродливым:
$anArray = array("theFirstItem" => "a first item");
if($condition) {
$anArray['conditionalItem'] = "it may appear base on the condition";
}
$anArray['theLastItem'] = "the last item";
Вы можете сделать это немного более удобным для чтения:
$anArray = array();
$anArray['theFirstItem'] = "a first item";
if($condition) {
$anArray['conditionalItem'] = "it may appear base on the condition";
}
$anArray['theLastItem'] = "the last item";
Ответ 2
Вы можете сделать это следующим образом:
$anArray = array(1 => 'first');
if (true) $anArray['cond'] = 'true';
$anArray['last'] = 'last';
Однако, вы не хотите.
Ответ 3
Если вы создаете чисто ассоциативный массив, а порядок ключей не имеет значения, вы всегда можете условно назвать ключ, используя синтаксис тернарного оператора.
$anArray = array(
"theFirstItem" => "a first item",
(true ? "conditionalItem" : "") => (true ? "it may appear base on the condition" : ""),
"theLastItem" => "the last item"
);
Таким образом, если условие выполнено, ключ существует с данными. Если нет, это просто пустой ключ с пустым строковым значением. Однако, учитывая большой список других ответов, может быть лучший вариант, соответствующий вашим потребностям. Это не совсем чисто, но если вы работаете над проектом с большими массивами, это может быть проще, чем вырваться из массива, а затем добавить потом; особенно если массив является многомерным.
Ответ 4
Здесь нет волшебства. Лучшее, что вы можете сделать, это следующее:
$anArray = array("theFirstItem" => "a first item");
if (true) {
$anArray["conditionalItem"] = "it may appear base on the condition";
}
$anArray["theLastItem"] = "the last item";
Если вам не особо понравился порядок предметов, он становится немного более терпимым:
$anArray = array(
"theFirstItem" => "a first item",
"theLastItem" => "the last item"
);
if (true) {
$anArray["conditionalItem"] = "it may appear base on the condition";
}
Или, если порядок имеет значение, а условные элементы больше пары, вы можете сделать это, что можно считать более читаемым:
$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
Попробуйте это, если у вас есть ассоциативный массив с разными ключами:
$someArray = [
"theFirstItem" => "a first item",
] +
$condition
? [
"conditionalItem" => "it may appear base on the condition"
]
: [ /* empty array if false */
] +
[
"theLastItem" => "the last item",
];
или это если массив не ассоциативный
$someArray = array_merge(
[
"a first item",
],
$condition
? [
"it may appear base on the condition"
]
: [ /* empty array if false */
],
[
"the last item",
]
);
Ответ 6
Вы можете назначить все значения и фильтровать пустые ключи из массива сразу:
$anArray = array_filter([
"theFirstItem" => "a first item",
"conditionalItem" => $condition ? "it may appear base on the condition" : NULL,
"theLastItem" => "the last item"
]);
Это позволяет вам избежать дополнительных условных после факта, поддерживать порядок клавиш и сделать его достаточно читаемым. Единственное предостережение здесь в том, что если у вас есть другие значения фальшивки (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; });
Ответ 7
Вы можете сделать это так:
$anArray = array(
"theFirstItem" => "a first item",
(true ? "conditionalItem" : "EMPTY") => (true ? "it may appear base on the condition" : "EMPTY"),
"theLastItem" => "the last item"
);
сбросить элемент массива EMPTY, если условие ложно
unset($anArray['EMPTY']);