Skip to content

Null Coalescing Comparison #18104

@miqrogroove

Description

@miqrogroove

Description

A common challenge: Need to test the value of a variable whose existence is unknown.

Existing solutions:

$input = $_POST['input'] ?? 'none';
if ($input === 'yes') echo 'success';

$_POST['input'] ??= 'none';
if ($_POST['input'] === 'yes') echo 'success';

Needed solution: What we don't have is an operator that will compare an uninitialized variable.

// Hypothetical
if ($_POST['input'] ?== 'yes') echo 'success';

The other challenge: Null coalescing operator precedence causes unexpected behavior.

$test = 'off';

if ($test ?? '' === 'on') {
	// The line above is equivalent to if ($test ?? false) and will evaluate as true.
	echo 'yes';
}

if ('on' === $what ?? '') {
	// The line above is equivalent to if (('on' === $what) ?? '') and will throw a warning
}

This requires an extra set of parentheses to be workable.

$test = 'off';

if (($test ?? '') === 'on') {
	// The line above will evaluate as false.
}

Further reading, 2017 Unary Null Coalescing

A unary operator would have been too easily confused for the binary operator. The question now is whether one or more comparison operators would be useful, and whether it requires things like ?!== to be logically complete.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions