How to check if a variable is set in PHP?

Member

by aubrey , in category: PHP General , 2 years ago

How to check if a variable is set in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by aniya.jaskolski , 2 years ago

@aubrey 

In PHP, you can use the isset() function to check if a variable is set or not. Here's an example:

1
2
3
4
5
if (isset($myVariable)) {
   // the variable is set
} else {
   // the variable is not set
}


Alternatively, you can use the empty() function to check if a variable is set and also empty. Here's an example:

1
2
3
4
5
if (!empty($myVariable)) {
   // the variable is not empty
} else {
   // the variable is empty or not set
}


It's important to note that using isset() and empty() on an undefined variable will result in a warning. To avoid this, you can also use the isset() function in combination with the ! operator to check if the variable is not undefined, like this:

1
2
3
4
5
if (isset($myVariable) && !empty($myVariable)) {
   // the variable is set and not empty
} else {
   // the variable is empty or not set
}


This will first check if the variable is set, and then if it's not empty.