PHP isset and empty

PHP isset and empty

Last Updated on Mar 21, 2023

What are they?

isset and empty are two functions that help us check the existence of a value. They are way more useful than you think.

isset

isset checks if a value has been set and it’s not null. If it’s undefined then it will return false otherwise it will return true. for example:

$twitter = 'Pratham';
isset($twitter);    // true
isset($css);        // false

isset($css) returns false because it has not been defined at all.

empty

empty checks if a value has been set and it’s not undefined like isset function. But it also checks if the value is not a false value.

For example an empty array or 0 or empty string. All of them would be considered as empty.

$twitter = 'Pratham';
$js = null;
$web3 = 0;
$eth = false;
empty($twitter);    // false
empty($css);        // true
empty($js);             // true
empty($web3);       // true
empty($eth);        // true

Opposite

Since empty and isset both return a value you can use ! to check for the opposite.

For example if we want to say check if $twitter is not empty Or check if $twitter is not set we can write:

If (!empty($twitter)){

}
Or check if $twitter is not set
If (!isset($twitter)){

}

Use case

So when do we use it?

We use it a lot.

For example let’s say we have a form and user has submitted the form and in the backend we are checking if the username and password has been submitted

We want to say check if user is not empty and password is not empty

if(!empty($username) && !empty($password)){
    // do something
}
https://youtu.be/mZXXYjPSkdU

Conclusion

Now you know about isset and empty functions in PHP.

I recommend you to open a PHP files and try define multiple variables. then try to check the return value of empty and isset on those variables.

If you have any suggestions, questions, or opinions, please contact me. I’m looking forward to hearing from you!

Key takeaways

  • isset in PHP
  • empty in PHP

 

Category: programming

Tags: #php

Join the Newsletter

Subscribe to get my latest content by email.

I won't send you spam. Unsubscribe at any time.

Related Posts

Courses