Menu

Add Topic

programming

waiting answer July 28, 2021

How to Check if a Key Exists in an Array PHP

I have an array of values. I want to check the key 0 or any other key-value exists in an array or not. How to check this.

Answers
February 09, 2021

The function array_key_exists() checks an array for a specified key. The output of this function is true or false. If the key-value exists, then it returns true. Else returns false.

    <?php
     $array=array("value1","value2");
     if(array_key_exists(0, $array)){
         echo "Key value exists";
     }else{
         echo "Key not exists";
     }  
    ?>
0 0
February 09, 2021

The array_key_exists() function is used to check whether a specified key is present in an array or not.

Syntax:

           array_key_exists(array_key, name_of_array)

  • key_array is the value to check
  • name_of_array is the name of the array

Program to checkmark of Sandeep using array_key_exists

    <?php
    $array=array("Ashok" => 50, "John" => 70, "Mathew" => 100);
    if (array_key_exists("Ashok",$array)){
        echo "Array key exists";
    }else{
        echo "Array key not exists";
    }
    ?>
0 0
February 09, 2021
     <?php
        $search_array = array('no_1' => 1, 'no_2' => 2,'no_3' => 3);
        if (array_key_exists('no_1', $search_array)) {
            echo "The 'no_1' element is in the array";
        }else{
            echo "Key element no_1 not exists";
        }
    ?>
0 0
May 27, 2021

Using 2 methods in PHP, We can check a key exist in an array in PHP

  1. array_key_exists() Method
  2. isset() Method

Using array_key_exists() method:

The array_key_exists() function checks whether an index or key is present inside an array or not.

Example:

     array("America", "Europe", "UAE"), 
          'country_rank' => array('1', '2', '3')
        ); 
          
        // Use of array_key_exists() function
        if(array_key_exists("country_rank", $array)) {
            echo "Key Exists"; 
        } else{ 
            echo "Key Not exist"; 
        }    
    ?>

Using isset() Method:

This function is used to check whether a key or index exists inside an array or not.

Example:

     array("America", "Europe", "UAE"), 
          'country_rank' => array('1', '2', '3')
        );  
        // Use of array_key_exists() function
        if(isset($array["country_rank"])){
            echo "Key Exists"; 
        }else{ 
            echo "Key Not Exists"; 
        } 
    ?>
0 0

Please Login to Post the answer

Leave an Answer