What is a double question mark in PHP?

by audrey.hodkiewicz , in category: PHP , 2 years ago

What is a double question mark in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by freddy , 2 years ago

@audrey.hodkiewicz The double question marks are short syntax for the isset() function and the quickest way to check if a variable exists is to use the value, otherwise some default value. Look into the code as an example in PHP below:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<?php

$name = $username ?? 'unknown';

// Output: unknown
echo $name;

// Equivalent to
$name = isset($username) ? $username : 'unknown';

// Output: unknown
echo $name;


Member

by wiley , 7 months ago

@audrey.hodkiewicz 

In the example above, the double question mark operator checks if the variable $username exists. If it does, it assigns its value to the $name variable. If it does not exist, it assigns the value 'unknown' to the $name variable. The double question mark operator in this context is a shorthand way of using the isset() function along with the ternary operator.