Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP shorthand for isset()? [duplicate]

Is there a shorthand way to assign a variable to something if it doesn't exist in PHP?

if(!isset($var) {   $var = ""; } 

I'd like to do something like

$var = $var | ""; 
like image 405
brentonstrine Avatar asked Sep 03 '13 23:09

brentonstrine


People also ask

What is isset ($_ GET?

Definition and Usage The isset() function checks whether a variable is set, which means that it has to be declared and is not NULL. This function returns true if the variable exists and is not NULL, otherwise it returns false.

What can I use instead of isset in PHP?

The equivalent of isset($var) for a function return value is func() === null . isset basically does a !== null comparison, without throwing an error if the tested variable does not exist.

How use isset with ternary operator in PHP?

"default-value"; // which is synonymous to: $var = isset($array["key"]) ? $array["key"] : "default-value"; In PHP 5.3+, if all you are checking on is a "truthy" value, you can use the "Elvis operator" (note that this does not check isset).

What is difference between isset and empty in PHP?

The isset() function is an inbuilt function in PHP that is used to determine if the variable is declared and its value is not equal to NULL. The empty() function is an inbuilt function in PHP that is used to check whether a variable is empty or not.


1 Answers

Update for PHP 7 (thanks shock_gone_wild)

PHP 7 introduces the null coalescing operator which simplifies the below statements to:

$var = $var ?? "default"; 

Before PHP 7

No, there is no special operator or special syntax for this. However, you could use the ternary operator:

$var = isset($var) ? $var : "default"; 

Or like this:

isset($var) ?: $var = 'default'; 
like image 123
hek2mgl Avatar answered Sep 23 '22 11:09

hek2mgl