Conditional Array Element Addition
In PHP, the task of conditionally adding an element to an associative array can be a challenge. For instance, consider the following array:
<code class="php">$arr = ['a' => 'abc'];</code>
How can we conditionally add 'b' => 'xyz' to this array using the array() statement? The ternary operator is not a viable option in this case.
PHP 8.1 Solution
One approach available in PHP 8.1 and higher involves using array unpacking:
<code class="php">$arr = [ 'foo' => 'bar', ...($condition ? ['baz' => 'boo'] : []), ];</code>
In this code:
This syntax allows for a concise and elegant way to conditionally add elements to an array.
The above is the detailed content of How to Conditionally Add Elements to an Associative Array in PHP 8.1?. For more information, please follow other related articles on the PHP Chinese website!