Greetings, internals!
In my practice, it is a very common case when I need to create an
associative array with varying structure, by that meaning that some
fields in the array are optional and are set conditionally. And of all
conditions the most frequent is checking for null-values: if the value
is null, then this field should be omitted from the final result.
Unfortunately, PHP currently does not offer any shorthand syntax for
declaring such fields in a compact way. In most cases for each of such fields
we need to have a dedicated "if", like:
// $array is first filled with all required fields
// Then we add all optional fields based on some condition
if ($value !== null) {
$array['field'] = $value;
}
This often leads to cumbersome code.
My proposal, which already has a prototype implementation, is following.
When declaring an associative array, add a new null-coalescing double
arrow for the fields which should be omitted if the value is null:
$array = [
'field1' => $param1,
'field2' => $param2,
'field3' ?=> $param3,
];
In this case, if $param3 === null, the created array would only
contain 'field1' and 'field2' from start, without the need to later
get rid of 'field3'.
This syntax will also allow more generalized conditions. For example,
instead of:
if ($someCondition) {
$array['field'] = $value;
}
You could create such array from start, if you are OK with such code-style:
$array = [
// other fields
'field' ?=> $someCondition ? $value : null,
];
The token '?=>' given here is mainly just an example, because the
exact form should be discussed anyway (this one, as well as others,
have pros and cons).
So, before I create an RFC for this feature, I would like to get
initial feedback: would this feature be welcome in general?
Prototype implementation for it:
https://github.com/Amegatron/php-src/tree/conditional-array-elements
Or just the diff with current master:
https://github.com/php/php-src/compare/master...Amegatron:php-src:conditional-array-elements
This is still a prototype though, some additional work must be done of
course, not counting the tests.
A slightly bigger example:
https://gist.github.com/Amegatron/06da8770e46e116b05f1c290cb0d56fc
Looking forward to your feedback.
Cheers,
Alexander Egorov.