Saturday, April 4, 2026
HomeLanguagesHow to check an element is exists in array or not in...

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 : 

  • element: The element to check in the array
  • array: The array to look for element

Example:

PHP




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




<?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.
RELATED ARTICLES

Most Popular

Dominic
32512 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6886 POSTS0 COMMENTS
Nicole Veronica
12007 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12100 POSTS0 COMMENTS
Shaida Kate Naidoo
7015 POSTS0 COMMENTS
Ted Musemwa
7259 POSTS0 COMMENTS
Thapelo Manthata
6972 POSTS0 COMMENTS
Umr Jansen
6960 POSTS0 COMMENTS