PHP array_key_exists() Function Example

PHP Script:


<?php
$sample_arr1 = array("a"=>"Codeigniter","b"=>"CakePHP","c"=>"Yui");
$sample_arr2 = array("Codeigniter","CakePHP","Yui");

if(array_key_exists("a",$sample_arr1))
{
echo "Key exists and contains value: ".$sample_arr1["a"];
}
else
{
echo "Key does not exist.";
}

if(array_key_exists(1,$sample_arr2))
{
echo " <br >Key exists and contains value: ".$sample_arr2[1];
}
else
{
echo "Key does not exist.";
}
?>

Output:


Key exists and contains value: Codeigniter
Key exists and contains value: CakePHP

Description:

PHP array_key_exists() function is used to check an array for a specified key if the key exist then true is return if not exist then false is return.
As shown in above example script key a is exists in array $sample_arr1 so this function return true.
And array $sample_arr2 have no keys so by default integer keys [0,1,2] are generated automatically because array contains 3 elements. And we check key “1” whether it is exist or not so the function returns true because key 1 exists.

PHP array_key_exists() function parameters:

1- Key: Specifies the key for checking whether it is exists or not.
2- Array: The array which is going to be checked against specified key.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s