Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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: 
 

php




<?php
//array containing 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";
}
?>


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.
 

php




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


Output: 
 

not found 
found 
found 

Program 3: 
 

php




<?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";
}
?>


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.
 



Last Updated : 27 May, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads