"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Published on 2024-11-08
Browse:842

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:

$arr = ['a' => 'abc'];

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:

$arr = [
    'foo' => 'bar',
    ...($condition ? ['baz' => 'boo'] : []),
];

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3