Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

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

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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.

My Personal Notes arrow_drop_up
Last Updated : 31 Oct, 2021
Like Article
Save Article
Similar Reads
Related Tutorials