PHP array_key_exists() Function

In this tutorial, we will learn about array_key_exists() function in PHP. Hope this tutorial will be helpful for you and I will try to cover all information in detail. Hope you liked this tutorial and this will be helpful for you.

PHP array_key_exists() function

In PHP array_key_exists() function is used to check for a particular key in a given array. If that key exists in an array then it will return true else it will return false.

Syntax:

array_key_exists(elementToSearch, givenArray);

Suppose an array is given that consists of an array of student names. we need to check that a particular student is present on the list. For that, we can make use of the array_key_exists() function. if the student’s name is present in the list, the function will return true else return false.

Let’s see with example code more clearly.

<?php
$studentList=array("Shristi"=>"10","Shaurya"=>"15","Dinesh"=>"20",);
if (array_key_exists("Shubho",$studentList))
  {
  echo "Key exists!";
  }
else
  {
  echo "Key does not exist!";
  }
?>
OUTPUT
The key does not exist!

The above results in false for a given function as the given key does not present in the array.

<?php
$studentList=array("Shristi"=>"10","Shaurya"=>"15","Dinesh"=>"20",);
if (array_key_exists("Shaurya",$studentList))
  {
  echo "Key exists!";
  }
else
  {
  echo "Key does not exist!";
  }
?>
OUTPUT:
Key exists!

Hope you liked this tutorial. Please do share.

Also Read: How to generate a random array in PHP

 

Leave a Reply

Your email address will not be published.