How to determine if an array contains a specific value in PHP?

Given an array and a specific value, we have to determine whether the array contains that value or not. So there is two popular way to determine that the specific value is in the array or not. One procedure is using by loop and other one is in_array() function. By using loop to get the specific value present or not is time-consuming compared to in_array() function so here we will skip the loop one and use the in_array() function.

Below programs illustrate how to determine if an array contains a specific value:

Program 1:



filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
//array containig elements
$names = array('Geeks', 'for', 'Geeks');
  
//search element
$item = 'Geeks';
if(in_array($item, $names)){
        //the item is there
    echo "Your element founded";
}
else{
        //the item isn't there
    echo "Element is not found";
}
?>

chevron_right


Output:

Your element founded

Program 2: In this example the in_array function perform in strict mode, it will also check the type of array elements.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php 
$name = array("Python", "Java", "C#", 3); 
    
      //Seraching python
if (in_array("python", $name, TRUE)) 
  
  echo "found \n"
  
else
  
  echo "not found \n"
  
    
    //Seraching 3
if (in_array(3, $name, TRUE)) 
  
  echo "found \n"
  
else
  
  echo "not found \n"
  
    
  //Seraching Java
if (in_array("Java", $name, TRUE)) 
  
  echo "found \n"
  
else
  
  echo "not found \n"
  }  
?> 

chevron_right


Output:

not found 
found 
found 

Program 3:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
$arr= array('gfg', 1, 17);
  
if (in_array('gfg', $arr)) {
    echo " gfg \n";
}
  
if (in_array(18, $arr)) {
    echo "18 found with strict check\n";
}
?>

chevron_right


Output:

gfg 

In the above example, the array contains string “gfg” and two numbers 1 and 17. The if statement calls in_array() function which checks if the given item as the parameter is present in the given array or not. If the function returns true, the if statement is executed.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.