Skip to content

Add destructuring coalesce - #9747

Draft
bwoebi wants to merge 1 commit into
php:masterfrom
bwoebi:destructuring-coalesce
Draft

bwoebi wants to merge 1 commit into
php:masterfrom
bwoebi:destructuring-coalesce

Conversation

@bwoebi

@bwoebi bwoebi commented Oct 14, 2022 •

Copy link
Copy Markdown
Member

Allowing for [$a ?? $b] = $array;, where $a is assigned $b if the key in the array is null or missing.

RFC: https://wiki.php.net/rfc/destructuring_coalesce

@bwoebi
bwoebi force-pushed the destructuring-coalesce branch from 5c8e498 to c79b933 Compare October 14, 2022 14:44
@kandy

kandy commented Oct 14, 2022

Copy link
Copy Markdown

Is it like?

<?php
['a'=>$a, 'b'=>$b] = [...json_decode('{"a":2}', 1), ...['b'=>'def val']];
var_dump($a, $b);

@bwoebi

bwoebi commented Oct 15, 2022

Copy link
Copy Markdown
Member Author

@kandy In that particular scenario of a top-level dimension with string keys, where no null values are present, yes.

But array unpacking won't help you with integer keys (because it will re-index them, consecutively), it doesn't allow for any nested destructuring, is not usable inline as a foreach target, and does not handle nulls for you.

@rentalhost

Copy link
Copy Markdown

I like it!

But what should happen if:

[ $a ?? '123', $b ] = [];
[ $a ?? '123', $b ] = [ 1 ];
[ $a ?? '123', $b ] = [ 1, 2 ];

It also supports ?: operator?

[ $a ?: '123' ] = []; // so $a = '123'
[ $a ?: '123' ] = [ false ]; // so $a = '123'
[ $a ?: '123' ] = [ 456 ]; // so $a = 456

@mvorisek

Copy link
Copy Markdown
Contributor

I found this PR when looking for another. The RFC was declined, so I think this one can be closed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants