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

Linda Hamilton
Release: 2024-10-31 09:44:01
Original
745 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template