Expand To Show Full Article
What is isset in PHP and When to use it? - Fueling PHP
Skip to content
Home » What is isset in PHP and When to use it?

What is isset in PHP and When to use it?

What is isset and how to use it in your PHP code

isset() is a php function that checks whether a variable, element, or property has been set and exists. It helps prevent bugs that occur when trying to reference a key that doesn’t exist.

In my opinion, isset is one of those annoying PHP functions that has grown a love / hate relationship on me. It is a necessary function in PHP that has prevented many errors and saved so many headaches, but it is also annoying because other languages have better ways of handling the existence of an element. The end result is an if statement that is large and harder to read but more complete.

Scenario: Checking whether an element exists inside of an array

In the following example, I am getting a multidimensional array back from my restful API. Check to see if you are able to locate the code smell and what could cause an annoying bug 6 months down the road?

<?php 

function mapPieResponseToObject(Array $pieData)
{
   $pie = new Pie();
   $pie->name = $pieData['name'];
   $pie->rating = $pieData['rating'];
   $pie->recipe = new Recipe();
   $pie->recipe->ingredients = $pieData['recipe']['ingredients'];
   $pie->recipe->cookTime = $pieData['recipe']['cookTime'];

   return $pie;
}

If your answer was “What would happen if someone didn’t pass in a recipe array within the $pieData?” then you would be correct. My application would blow up on me if I tried to run that code and didn’t pass a recipe key inside the $pieData variable. There is no outright bug in the above code. If you always pass in the same expected data structure 100% of the time then all is well and good.

You’re happy path is established. but…

As you should know by now, the happy path is the least likely scenario to occur. 9 times out of 10 the data structure will change or someone will want to store a pie without recipe data. You need to be able to handle this situation. What do you do?

You check whether the recipe element is set isset in the PHP function before trying to access the elements within the recipe array.

<?php 

function mapPieResponseToObject(Array $pieData)
{
   $pie = new Pie();
   $pie->name = $pieData['name'];
   $pie->rating = $pieData['rating'];
   $pie->recipe = new Recipe();

   if (isset($pieData['recipe'])) {
       $pie->recipe->ingredients = $pieData['recipe']['ingredients'];
       $pie->recipe->cookTime = $pieData['recipe']['cookTime'];
   }
   return $pie;
}

Do you see the difference in this example I wrote? The isset checks whether the recipe key exists within the pieData PHP array before trying to access it or any child elements within the recipe object. I still have a recipe object within my pie object but the ingredients and cookTime are null because I skipped over them.

This may or may not for your requirements.

What if you need a default value for all the properties in your pie PHP object?

This is simple. Use a ternary to check whether the PHP array key isset and apply a default value when it is not. For example, let’s update the

function mapPieResponseToObject(Array $pieData): Pie
{
   // Let's check for the required values
   // if these don't exist, throw an Exception.
   if (!isset($pieData['name']) || !isset($pieData['rating']) {
      throw new Exception("Missing one or more required keys: name, rating");
   }

   $pie = new Pie();
   $pie->name = $pieData['name'];
   $pie->rating = isset($pieData['rating']) ? $pieData['rating'] : 0;
   $pie->recipe = new Recipe();

   if (isset($pieData['recipe'])) {
       $pie->recipe->ingredients = isset($pieData['recipe']['ingredients']) ?  $pieData['recipe']['ingredients'] : $this->getDefaultIngredients();
       $pie->recipe->cookTime = isset($pieData['recipe']['cookTime']) ? $pieData['recipe']['cookTime'] : $this->getDefaultCookTime();
   }

   return $pie;
}

In the above scenario, we made our code more robust and saved countless hours down the road by preventing future bugs with more isset checks. This is a complete win. The PHP code is robust and returns back a consistent data structure every time by using the isset function.

Bonus Scenario: Using isset to perform math requests

Big requests come in all the time to perform some math on your data objects. It can even get crazy complicated by having default values and logic whenever an element doesn’t exists or has a certain value. I use isset in this case a solid amount of time.

Scenario: I have some data to create a new pie object. The pie object should now have cost, quantity, orderRequests, and salePrice attached to it. the salePrice is calculated by using formula (cost * 1.30 * ( orderRequests / quantity + 1)) . The gotcha is that there isn’t always a quantity on my pieData array or it may be 0 which is the same as being empty. It needs to defaults to 5000. How do I accomplish this?

Let’s add some more isset checks and updates to our above PHP function.

function mapPieResponseToObject(Array $pieData): Pie
{
   // Let's check for the required values
   // if these don't exist, throw an Exception.
   if (!isset($pieData['name']) || !isset($pieData['rating'] || !isset($pieData['cost']) || !isset($pieData['orderRequests'])) {
      throw new Exception("Missing one or more required keys: name, rating, cost and orderRequests");
   }

   $pie = new Pie();
   $pie->name = $pieData['name'];
   $pie->rating = isset($pieData['rating']) ? $pieData['rating'] : 0;
   $pie->recipe = new Recipe();

   if (isset($pieData['recipe'])) {
       $pie->recipe->ingredients = isset($pieData['recipe']['ingredients']) ?  $pieData['recipe']['ingredients'] : $this->getDefaultIngredients();
       $pie->recipe->cookTime = isset($pieData['recipe']['cookTime']) ? $pieData['recipe']['cookTime'] : $this->getDefaultCookTime();
   }

  // Section to perform math operations and sales data
  // cost, quantity, orderRequests, and salePrice attached to it. the salePrice is calculated  by using formula (cost * 1.30 * ( orderRequests / quantity + 1))
  $pie->cost = $pieData['cost'];
  $pie->quantity = (isset($pieData['quantity']) && $pieData['quantity'] > 0) ? $pieData['quantity'] : 5000
  $pie->orderRequests = $pieData['orderRequests'];
  $pie->salePrice = $pie->cost * 1.30 * ( $pie->orderRequests / $pie->quantity + 1);

   return $pie;
}

We’ve added some good math to our function now and applied some good checks to ensure that our data is consistent with our business rules for years to come. If the data structure unexpectedly changes then the logic will throw errors and yell that it couldn’t fulfill the requirements.

Purpose if isset in PHP and Why I use it.

In the end, I use isset to check my data throughout my code. It helps me future-proof my code and prevent bugs that may occur due to data inconsistency. I prefer the way other languages handle checking for keys, elements or properties as they are more succinct, but this is the way to handle it within PHP. It may not be the prettiest function but it has a solid purpose that gets the job done.