Home >Backend Development >PHP Tutorial >How to Conditionally Add Elements to an Associative Array in PHP 8.1?

How to Conditionally Add Elements to an Associative Array in PHP 8.1?

Linda Hamilton
Linda HamiltonOriginal
2024-10-31 09:44:01806browse

How to Conditionally Add Elements to an Associative Array in PHP 8.1?

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:

  • The ... operator is used for array unpacking.
  • The ternary operator ($condition ? ['baz' => 'boo'] : []) conditionally returns an array with 'baz' => 'boo' if $condition is true; otherwise, it returns an empty array.
  • The unpacking operator then merges the result of the ternary operator with the existing array.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn