Friday, October 10, 2025
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
32349 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6717 POSTS0 COMMENTS
Nicole Veronica
11880 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11941 POSTS0 COMMENTS
Shaida Kate Naidoo
6838 POSTS0 COMMENTS
Ted Musemwa
7097 POSTS0 COMMENTS
Thapelo Manthata
6792 POSTS0 COMMENTS
Umr Jansen
6792 POSTS0 COMMENTS