PHP Array array_key_exists() Function (With Examples)

In this tutorial, we will learn about the PHP array_key_exists() function with its usage, syntax, parameters, return value, and examples. By IncludeHelp Last updated : December 31, 2023

PHP array_key_exists() function

The 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

The syntax of the array_key_exists() function:

array_key_exists(key, array);

Parameters

The parameters of the array_key_exists() function:

  • key is the value of the key to be checked.
  • array is an input array, in which key will be checked.

Return Value

The return type of this method is bool, it returns true on success or false on failure.

Sample Input/Output

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

PHP array_key_exists() Function Example

<?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

The output of the above example is:

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

To understand the above example, you should have the basic knowledge of the following PHP topics:

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.