Wednesday, 24 September 2014

array_key_exists in PHP

array_key_exists function checks the input key is exists in a given array if key available in the array then the function returns true.

Syntax: array_key_exists(key,array)

Parameters Description:
key : Required. Define the key.
array : Required. Define an array.

Tip: if key not defined in an array then an integer key is returned to starting 0.

Example:

<?php
$daysarr1 = array("a"=>"Sunday","b"=>"Monday");
if(array_key_exists("b",$daysarr1))
{
       echo " "b" Key Exists in array $daysarr1"."<br />";
}
else
{
        echo " "b" Key does not exists in array $daysarr1"."<br />";
}
$daysarr2 = array("a"=>"Sunday","b"=>"Monday");
if(array_key_exists("c",$daysarr2))
{
       echo " "c" Key Exists in array $daysarr2"."<br />";
}
else
{
         echo " "c" Key does not exists in array $daysarr2"."<br />";
}
$daysarr3 = array("Sunday","Monday");
if(array_key_exists(0,$daysarr3))
{
         echo " 0 Key Exists in array $daysarr3"."<br />";
}
else
{
           echo " 0 Key does not exists in array $daysarr3"."<br />";
}
?>

O/P:


"b" Key Exists in array $daysarr1
"c" Key does not exists in array $daysarr2
0 Key Exists in array $daysarr3

0 comments:

Post a Comment