PHP - empty and isset functions

Introduction

There are two useful functions for inquiring about the content of an array.

To know if an array contains any element at all, use the empty function.

empty function works with strings too, an empty string is 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:

Demo

<?php
    $string = ''; 
    $array = []; 
    $names = ['A', 'B', 'C']; 
    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 
?>/*ww  w  .  j a  v a  2 s. c o m*/

Result

Here, 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: C.

Finally, isset($names[3]) evaluates to false as the key 3 does not exist in that array.

Related Topic