empty and isset functions in PHP

There are two useful functions for enquiring about the content of an array. If you want to know if an array contains any element at all, one can ask if it is empty with the empty function.

ISSET returns TRUE if the variable exists and has a value other than NULL. That means variables assigned a “”, 0, “0”, or FALSE are set, and therefore are TRUE for ISSET . EMPTY checks to see if a variable is empty.

The function actually works with strings too, an empty string being a string with no characters (‘ ‘). The isset function takes an array position, and returns true or false depending on whether that position exists or not:

<?php
$string = '';
$array = [];
$names = ['Harry', 'Ron', 'Hermione'];
var_dump(empty($string)); // true
var_dump(empty($array)); // true
var_dump(empty($names)); // false
var_dump(isset($names[2])); // true
var_dump(isset($names[3])); // false

In the preceding example, we can see that an array with no elements or a string with no characters will return true when asked if it is empty, and false otherwise.

When we use isset($names[2]) to check if the position 2 of the array exists, we get true, as there is a value for that key: Hermione. Finally, isset($names[3]) evaluates to false as the key 3 does not exist in that array.


Searching for elements in an array

Probably, one of the most used functions with arrays is in_array. This function takes two values, the value that we want to search for and the array. The function returns true if the value is in the array and false otherwise.

This is very useful, because a lot of times what we want to know from a list or a map is if it contains an element, rather than knowing that it does or its location.

Even more useful sometimes is array_search. This function works in the same way except that instead of returning a Boolean, it returns the key where the value is found, or false otherwise.

Let’s see both functions:

<?php
$names = ['Harry', 'Ron', 'Hermione'];
$containsHermione = in_array('Hermione', $names);
var_dump($containsHermione); // true
$containsSnape = in_array('Snape', $names);
var_dump($containsSnape); // false
$wheresRon = array_search('Ron', $names);
var_dump($wheresRon); // 1
$wheresVoldemort = array_search('Voldemort', $names);
var_dump($wheresVoldemort); // false

This is all about the empty and isset functions in PHP.

Leave a Comment

Your email address will not be published. Required fields are marked *