Open In App

PHP in_array() Function

Improve
Improve
Like Article
Like
Save
Share
Report

The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise. 

Syntax:

bool in_array( $val, $array_name, $mode )

Parameters:

  • $val: value that needs to be searched it can be of any type. if the type is a string then it will check in a case-sensitive manner.
  • $array_name: Name of the array from which the value will be searched for.
  • $mode: This is an optional parameter and is of boolean type. This parameter specifies the mode in which we want to perform the search. If it is set to TRUE, then the in_array() function searches for the value with the same type of value as specified by the $val parameter. The default value of this parameter is FALSE.

Return Value:

The in_array() function returns a boolean value i.e., TRUE if the value $val is found in the array otherwise it returns FALSE.

Approach:

  • In order to search an array for a specific value, we will be using the in_array() function where the parameter for the search is of string type & its value is set to true.
  • Otherwise, this function returns a false value if the specified value is not found in an array.

Example 1: The below program performs the search using the in_array() function in non-strict mode ie, the last parameter $mode is set to false which is its default value. The value to be searched is of string type whereas this value in the array is of integer type still the in_array() function returns true as the search is in non-strict mode.

PHP




<?php
    
$marks = array(100, 65, 70, 87);
  
if (in_array("100", $marks)) {
    echo "found";
} else {
    echo "not found";
}
  
?>


Output

found

Example 2: The below program performs the search using the in_array() function in strict mode ie., the last parameter $mode is set to true and the function will now also check the type of values.

PHP




<?php
    
$name = array("ravi", "ram", "rani", 87);
  
if (in_array("ravi", $name, TRUE)) {
    echo "found \n";
} else {
    echo "not found \n";
}
  
if (in_array(87, $name, TRUE)) {
    echo "found \n";
} else {
    echo "not found \n";
}
  
if (in_array("87", $name, TRUE)) {
    echo "found \n";
} else {
    echo "not found \n";
}
?>


Output

found 
found 
not found 

Referencehttp://php.net/manual/en/function.in-array.php

PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.



Last Updated : 20 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads