array_key_exists


php128 apg

CHECKS if the given key or index exists in the given ARRAY.

This function is an alias of key_exists.



key_exists


CHECKS if the given key or index exists in the given ARRAY.

This function is an alias of array_key_exists.





This function returns TRUE on SUCCESS or FALSE on FAILURE.

This function will search for the keys in the first dimension only.

Nested keys in multidimensional arrays will not be found.



<?php

bool array_key_exists 
mix $key arr $array )

or

bool key_exists mix $key arr $array )

where,

$key The given value to check

$array 
The given ARRAY with key to check

?>

 $key 


The value to be checked.



 $array 


An ARRAY to check.



  1 EXERCISE   

<?php

$key01a 
'continents';

$key01b 'countries';

$key01c 'capitals';


function 
searchkey($key)
{
    
 
$var01 = ['continents' => ['South America''Europe'], 
                        
'countries' => ['Brasil''Portugal']];
                        
 if(
array_key_exists($key$var01))
         {
         echo 
'<br><br>The index:<br>' $key 
         
'<br>WAS found in ARRAY:<br>';
         
print_r($var01);
         }
         else
         {
         echo 
'<br><br>The index:<br>' $key 
         
'<br>WAS NOT found in ARRAY:<br>';
         
print_r($var01);
         }
}

searchkey($key01a);

searchkey($key01b);

searchkey($key01c);
     
?>

 RESULT   

The index:
continents
WAS found in ARRAY:
Array ( [continents] => Array ( [0] => South America [1] => Europe ) [countries] => Array ( [0] => Brasil [1] => Portugal ) )

The index:
countries
WAS found in ARRAY:
Array ( [continents] => Array ( [0] => South America [1] => Europe ) [countries] => Array ( [0] => Brasil [1] => Portugal ) )

The index:
capitals
WAS NOT found in ARRAY:
Array ( [continents] => Array ( [0] => South America [1] => Europe ) [countries] => Array ( [0] => Brasil [1] => Portugal ) )


  2 EXERCISE   

<?php

$key02a 
'key';
$key02b 'val';

function 
arrkeyexists02 ($k02)
{
    
$arr02 = ['one''key' => 'value''val'];
    
    if(
array_key_exists($k02$arr02))
     {
         
         
         echo 
'<br><br>The index:<br>' $k02 
         
'<br>WAS found in ARRAY:<br>';
         
print_r($arr02);
         }
         else
         {
         echo 
'<br><br>The index:<br>' $k02 
         
'<br>WAS NOT found in ARRAY:<br>';
         
print_r($arr02);
         } 
}

arrkeyexists02 ($key02a);

arrkeyexists02 ($key02b);

?>

 RESULT   

The index:
key
WAS found in ARRAY:
Array ( [0] => one [key] => value [1] => val )

The index:
val
WAS NOT found in ARRAY:
Array ( [0] => one [key] => value [1] => val )