PHP array_key_exists() function with example

PHP array_key_exists() function with example

array_key_exists() function is used to check whether an array contains the given key or not. If key exists in the array – it returns true if the key does not exist in the array – it returns false.

Syntax:

 array_key_exists(key, array);

Examples:

 Input:
    $arr = array("name" => "Amit", "age" => 21, "city" => "Gwalior");
   
    Output:
    array_key_exists("age", $arr): true
    array_key_exists("gender", $arr): false

PHP Code:

<?php
    $arr = array("name" => "Amit", "age" => 21, "city" => "Gwalior");
    
    //checking a key "age"
    if(array_key_exists("age", $arr)){
        print("array contains the key \"age\"\n");
    }
    else{
        print("array does not contain the key \"age\"\n");
    }

    //checking a key "gender"
    if(array_key_exists("gender", $arr)){
        print("array contains the key \"gender\"\n");
    }
    else{
        print("array does not contain the key \"gender\"\n");
    }        
?>

Output:

array contains the key "age"
array does not contain the key "gender"

Recent Posts

error: Alert: Content is protected!!