Как добавить условие внутри массива 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 ')' 

К сожалению, это вообще невозможно.

Если наличие элемента, но с нулевым значением, это нормально, используйте это:

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

Если вы создаете чисто ассоциативный массив, а порядок ключей не имеет значения, вы всегда можете условно назвать ключ, используя синтаксис тернарного оператора.

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

Таким образом, если условие выполнено, ключ существует с данными. Если нет, это просто пустой ключ с пустым строковым значением. Однако, учитывая большой список других ответов, может быть лучший вариант, соответствующий вашим потребностям. Это не совсем чисто, но если вы работаете над проектом с большими массивами, это может быть проще, чем вырваться из массива, а затем добавить потом; особенно если массив является многомерным.

Вы можете сделать это так:

 $anArray = array(1 => 'first'); if (true) $anArray['cond'] = 'true'; $anArray['last'] = 'last'; 

Однако то, что вы хотите, невозможно.

Здесь нет никакой магии. Лучшее, что вы можете сделать, это:

 $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 с $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 

Попробуйте это, если у вас есть ассоциативный массив с разными ключами:

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

Вы можете назначать все значения и фильтровать пустые ключи из массива одновременно:

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

Это позволяет вам избежать дополнительных условных после факта, поддерживать порядок клавиш, и imo это достаточно читаемо. Единственное предостережение здесь в том, что если у вас есть другие значения фальши ( 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; });