PHP’s isset, empty, and is_null: Our friendly assets

jochelle mendonca
2 min readJan 25, 2024

--

Photo by MedicAlert UK on Unsplash

One most have definitely come across PHP’s most commonly used conditionals — isset, empty, and is_null .

But have you ever found yourself scratching your head wondering which one to use when?

Fear not! I’ve been there, done that, and I’m here to shed some light on these trusty tools.

Understanding the Basics:

  1. isset: isset is your go-to detective. It’s like asking, “Hey, is this variable set and not null?”

It returns true if the variable exists and has a value other than null.

2. empty: Now, empty is like your reliable Swiss army knife. It checks if a variable is empty, meaning it’s either null, an empty string, 0, or an empty array.

It’s your one-stop-shop for checking if something’s, well, empty!

3. is_null: Last but not least, is_null is your straightforward buddy. It simply checks if a variable is null — nothing more, nothing less.

Tips and Tricks from the Trenches:

1. Choosing the Right Tool:

  • Use isset when you want to check if a variable exists and has a non-null value. It’s perfect for avoiding “undefined variable” errors.
  • Reach for empty when you want to check if a variable is “empty” in the broad sense — null, empty string, 0, or an empty array.
  • Reserve is_null for situations where you specifically need to know if a variable is null and nothing else.

2. Be Careful with empty:

  • Remember that empty considers 0 and “0” as empty values, which might not always be what you expect. Double-check your logic to avoid surprises!

3. Leverage isset for Safe Access:

  • Use isset to safely access array keys or object properties without triggering “undefined index” or “undefined property” errors.

4. Keep it Simple:

  • When in doubt, go for the simplest solution. isset, empty, and is_null are your trusty allies, so don’t overcomplicate things!

So there you have it, isset, empty, and is_null in PHP may seem like simple tools, but mastering them can save you from many headaches down the road.

If you like the article and would like to support me, make sure to:

  • 👏Clap for this story
  • 🔔Follow me on Medium
  • ☕️ If you feel my work is worth an appreciation, you can buy me a coffee!

--

--

jochelle mendonca

Passionate PHP developer. Enthusiastic about the power of words, equally adept at reading and writing