Check if an index exists in array in PHP

This tutorial will discuss about unique ways to check if an index exists in array in php.

Table Of Contents

Method 1: Using array_key_exists() function

The array_key_exists() function in PHP accepts an index/key and an array as arguments. It checks if the given array contains the given key or index. If yes, then it returns true, otherwise it returns false.

We can use this to check if a given index is valid or not i.e. it exists in the array or not.

Let’s see the complete example,

<?php
$arr = array('for', 'why', 'this', 'here', 'some');
$index = 2;

// Check if index is valid in array
if (array_key_exists($index, $arr))
{
    echo "The given Index exists in the array";
}
else
{
    echo "The given Index does not exists in the array";
}
?>

Output

The given Index exists in the array

Method 2: Using isset() function

Select element at given index from the array i.e. $arr[$index], and then pass it to the isset() function, to check if this is declared or not. If it is set and has any value other then null, then it will return true. This way we can check if an index is valid or not for an array.

Let’s see the complete example,

<?php
$arr = array('for', 'why', 'this', 'here', 'some');
$index = 2;

// Select the element at given index from array
// and check it is set i.e. if index is valid
if (isset($arr[$index]))
{
    echo "The given Index exists in the array";
}
else
{
    echo "The given Index does not exists in the array";
}
?>

Output

The given Index exists in the array

Summary

We learned two ways to check if an index exists in an array or not.

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top