Home » PHP

PHP array_key_exists() function with example

PHP array_key_exists() function: Here, we are going to learn about the array_key_exists() function with example in PHP.
Submitted by IncludeHelp, on February 15, 2019

PHP array_key_exists() function

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);

Here,

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

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"





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.