Open In App

How to check an element is exists in array or not in PHP ?

An array may contain elements belonging to different data types, integer, character, or logical type. The values can then be inspected in the array using various in-built methods :

Approach 1 (Using in_array() method): The array() method can be used to declare an array. The in_array() method in PHP is used to check the presence of an element in the array. The method returns true or false depending on whether the element exists in the array or not. 



in_array(element , array)

Arguments : 

Example:






<?php
  
// Declaring an array object 
$arr = array("Hello", "GEEKs" , "User" , "PHP");
print("Original Array </br>");
print (json_encode($arr) . " </br>");
  
// Declaring element
$ele = "GEEKs";
  
// Check if element exists
if(in_array($ele, $arr)){
    print($ele . " - Element found.");
}else{
    print($ele . "Element not found.");
}
?>

Output:

Original Array:
["Hello","GEEKs","User","PHP"]
GEEKs - Element found.

Approach 2 (Using for loop): A for loop iteration is done throughout the array. A boolean flag is declared to check for the presence of an element. It is initialized to the boolean value of false. In case the value is false, and the element is found in the array, the flag value is changed to the true value. No further modifications in the flag value are made. 

Example:




<?php
  
// Declaring an array object 
$arr = array(1, 3, 5, 6);
print("Original Array </br>");
print (json_encode($arr)." </br>");
  
// Declaring element
$ele = 5;
  
// Declare a flag 
$flag = FALSE;
  
// Check if element exists
foreach($arr as $val){
    if($flag == FALSE){
        if($val == $ele){
            $flag = TRUE;
        }
    }
}
if($flag ==TRUE){
    print($ele . " - Element found.");
}
else{
    print($ele . " - Element not found.");
}
?>

Output:

Original Array
[1, 3, 5, 6]
5 - Element found.

Article Tags :