What is PHP isset function and When to use it?

PHP isset function is often used to check if certain variables and arrays are set. These type of checks are crucial while building applications that rely on APIs. We’ll see a similar scenario of an Online Store API at the end of this article. 

But before that, we need to make sure we understand what PHP isset function is and then move on to see when to use it. Let’s begin with the description and syntax of the function, as the PHP documentation states it.

Syntax

PHP isset function determines if a variable is declared and is different than null.

Function Signature

isset(mixed $var, mixed …$vars) : bool

Arguments

  • $var – Variable to check
  • $vars – Further variables

Return Type

  • Returns true if var exists and has a value other than null, else returns false.

Note#1

For multiple parameters, the isset function returns true only if all these are set. It evaluates the parameters from left to right and returns false on encountering an unset variable.

Note#2

The isset function returns false instead of raising an exception or warning for an undeclared variable.

Examples of PHP isset function

Let’s explore the PHP isset function by examples.

Example#1 – Variables

We have several variables in the example and we’ll pass each of these to the isset function to see the output.

<?php
//Some variables.
$name = "Stacie";
$age  = 21;
$department = "";
 
//Use isset to check them. 
var_dump(isset($name));
var_dump(isset($age));
var_dump(isset($department));
 
 
/*
bool(true)
bool(true)
bool(true)
*/
?>

Some newbies might wonder why it returns true for the empty string variable. Well, by the definition of PHP isset function, it returns false for null only. An empty string is different than a null that’s why the function returns true.

There’s a way to refactor this code and shorten it. Remember we can pass multiple parameters to the isset function.

<?php
//Some variables.
$name = "Stacie";
$age  = 21;
$department = "";
 
//Use isset to check them. 
var_dump(isset($name,$age,$department));
 
/*
bool(true)
*/
?>

Cool. Since all the variables are set, It returns true. Well, before we move on to see arrays with isset, let’s see an example where the function returns false.

<?php
//Some variables.
$var_a = null;
 
//Use isset to check $var_a. 
var_dump(isset($var_a));
 
//OUTPUT
//bool(false)
?>

Nothing surprising because the variable is null and thus isset returns false.

Example#2 – Arrays

PHP isset function works the same way for array elements. Let’s see an example with an array.

<?php
//Array having employee data.
$arr = ["Name"=>"Mike","Department"=>"IT","Skills"=> ["PHP","Laravel","Wordpress","Bootstrap"]];
 
//Use isset to check the values. 
var_dump(isset($arr["Name"]));
var_dump(isset($arr["Department"]));
var_dump(isset($arr["Skills"]));
 
//OUTPUT
// bool(true)
// bool(true)
// bool(true)
?>

We check every value individually. We can refactor this code as we did in the previous example.

<?php
//Array having employee data.
$arr = ["Name"=>"Mike","Department"=>"IT","Skills"=> ["PHP","Laravel","Wordpress","Bootstrap"]];
 
//Use isset to check the values. 
var_dump(isset($arr["Name"],$arr["Department"],$arr["Skills"]));
 
//OUTPUT
// bool(true)
?>

So, the function returns true because all the values are set. This is pretty much all about the PHP isset function. Simple, isn’t it?


Next, we see a scenario where the isset function is helpful.

Scenario: Online Store API

Let’s assume we’re building an online store that deals in footwear. For that, we have an API for retrieving products data. The data includes price, size, and discounts (If applicable). The application calls the API and stores the response in an associative array.


Now, the catch here is that the discount may or may not be applicable. That’s why we always need to check the discount and apply it to the price. That’s an ideal scenario for using the PHP isset function, let’s see how.

<?php
include('store_api.php');
 
//Calls the API for retrieiving product(s) info.
$products = getProducts();
 
//Loop through the products and print them to console.
foreach ($products as $product) {
   
    echo "Product Name: ".$product["Product Name"]."\n";
    echo "Price: ".$product["Price(USD)"]." USD"."\n";
 
    //Checks if discount is applicable, sets it to "Not applicable" otherwise.
    if(isset($product["Discount(%)"])) {
        echo "Discount: ".$product["Discount(%)"]."%"."\n";
        //Computes the discounted price and prints it to console.
        echo "Discounted Price: ". round($product["Price(USD)"] - ($product["Price(USD)"] * ($product["Discount(%)"]/100)),2)." USD"."\n";
    }
 
    //If isset returns false that means the discount is not applicable.
    else {
        echo "Discount: Not applicable"."\n";
    }
 
    echo "========================================================================="."\n";
}
?>

Here’s the output.

Product Name: White Sneakers
Price: 40.44 USD
Discount: 10%
Discounted Price: 36.4 USD
=======================================================================
Product Name: Black Joggers
Price: 39.55 USD
Discount: Not applicable
=======================================================================

In the example, the IF/ELSE evaluates based on the output of isset. If the discount applies it definitely has a value, thus the isset returns true and the IF condition holds. Then, the code computes the discounted price and prints it to the console.

On the contrary, isset returns false if the discount is not applicable and thus we have a null value. The code then prints out “Discount: Not applicable”. This is an explanation of the example we’ve just seen. 


The main focus was to see where the PHP isset function fits in, which is clear now. That’s pretty much it, we hope you’ve enjoyed the article.

Want to explore further about PHP arrays?

We have many fun articles related to PHP arrays. You can explore these to learn more about arrays in PHP.

Convert array to string with PHP implode function

Make an associative array in PHP

Sort an array in PHP


Article Categories

Article Tags

    © 2023 Confident.Systems