Skip to content
Advertisement

Best way to give a variable a default value (simulate Perl ||, ||= )

I love doing this sort of thing in Perl: $foo = $bar || $baz to assign $baz to $foo if $bar is empty or undefined. You also have $foo ||= $bletch which will only assign $bletch to $foo if $foo is not defined or empty.

The ternary operator in this situation is tedious and tiresome. Surely there’s a simple, elegant method available in PHP?

Or is the only answer a custom function that uses isset()?

Advertisement

Answer

In PHP 7 we finally have a way to do this elegantly. It is called the Null coalescing operator. You can use it like this:

$name = $_GET['name'] ?? 'john doe';

This is equivalent to

$name = isset($_GET['name']) ? $_GET['name']:'john doe';
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement