How to check a key exist in array? Explain with example?

Posted by

We can check a key exist or not in an array with the help of array_key_exist() function in PHP. array_key_exists() function checks an array for a specified key, and returns true if the key exists and false if the key does not exist,  if we skip the key when we specify an array, an integer key is generated which starts at 0 and increases by 1 for each value.

syntax

array_key_exists(key, array)

this function takes two argument and this function returns boolean values(TRUE/FALSE), nested keys always return false value.

example1

<?php

        // with key values
		$shivam = array("shivam" => "23","ravi" => "24","abhi" => "25");
		
			if (array_key_exists("abhi",$shivam))
			{
				echo "Key exists";
			}
			else
			{
				echo "Key not exist";
			}
?> 

output

Key exists

example 2

<?php
       // with no key values
		$shivam = array("shivam","ravi","abhi");
		
			if (array_key_exists(0,$shivam))
			{
				echo "Key exists";
			}
			else
			{
				echo "Key not exist";
			}
?> 

output

Key exists
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x