Thursday, July 4, 2024
HomeLanguagesPhpHow to check a key exists in an array in PHP ?

How to check a key exists in an array in PHP ?

We have given an array arr and a Key key, the task is to check if a key exists in an array or not in PHP.

Examples:

Input : arr = ["Geek1", "Geek2", "1", "2","3"] 
        key = "2"
Output : Found the Key

Input : arr = ["Geek1", "Geek2", "1", "2","3"] 
        key = 9
Output : Key not Found

The problem can be solved using PHP inbuilt function for checking key exists in a given array. The in-built function used for the given problem are:

Method 1: Using array_key_exists() Method: The array_key_exists() function checks whether a specific key or index is present inside an array or not.

Syntax:

boolean array_key_exists( $index, $array )

Example:

PHP




<?php
// PHP program to check if a key 
// exists in an array or not
  
$array = array(
      'names' => array("Geek1", "Geek2", "Geek3"), 
    'rank' => array('1', '2', '3')
); 
  
// Use of array_key_exists() function
if(array_key_exists("rank", $array)) {
    echo "Found the Key"
else
    echo "Key not Found"
  
?>


Output

Found the Key

Method 2: Using isset() Method: The isset() function checks whether a specific key or index is present inside an array or not.

Syntax:

bool isset( mixed $var, mixed $... )

PHP




<?php
// PHP program to check if a key 
// exists in an array or not
  
$array = array(
      'names' => array("Geek1", "Geek2", "Geek3"), 
    'rank' => array('1', '2', '3')
); 
  
// Use of array_key_exists() function
if(isset($array["rank"])){
    echo "Found the Key"
else
    echo "Key not Found"
  
?>


Output

Found the Key 

Previous article
Next article
Nicole Veronica Rubhabha
Nicole Veronica Rubhabha
A highly competent and organized individual DotNet developer with a track record of architecting and developing web client-server applications. Recognized as a personable, dedicated performer who demonstrates innovation, communication, and teamwork to ensure quality and timely project completion. Expertise in C#, ASP.Net, MVC, LINQ, EF 6, Web Services, SQL Server, MySql, Web development,
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments