PHP in_array() Function

By IncludeHelp Last updated : February 25, 2024

Description and Usage

The in_array() function in PHP is used for checking if a value is present in an array.. It simplifies the process of searching arrays, making it easy to find out whether a particular value exists in the array or not.

Syntax

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

Parameters

  • $val: The value to be searched, which can be of any type. If the type is a string, the search is case-sensitive.
  • $array_name: The name of the array in which the value will be searched.
  • $mode (optional): The function has a boolean parameter, denoted as "search mode," which, when set to TRUE, instructs the function to seek a value matching the type specified by the $val parameter. By default, this parameter is set to FALSE.

Return Value

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

Example 1

Check if a specific number is present in an array.

<?php $numbers = [10, 20, 30, 40, 50];
$search_value = 30;
if (in_array($search_value, $numbers)) {
    echo "The number $search_value is present in the array.";
} else {
    echo "The number $search_value is not found in the array.";
}
?>

Output

The number 30 is present in the array. 

Explanation

In this example, the in_array() function is used to check if the value 30 is present in the array $numbers. The function returns TRUE, and the message "The number 30 is present in the array" is echoed.

Example 2

Verify if a specific string exists in an array in a case-sensitive manner.

<?php
$colors = ["red", "Green", "BLUE", "yellow"];
$search_color = "green";
if (in_array($search_color, $colors, true)) {
    echo "The colour $search_color is present in the array.";
} else {
    echo "The colour $search_color is not found in the array.";
}
?>

Output

The colour green is not found in the array. 

Explanation

Here, the in_array() function is used with the third parameter set to TRUE, indicating a case-sensitive search. As a result, the function returns FALSE, and the message "The colour green is not found in the array" is displayed.

To understand the above examples, you should have the knowledge of the following PHP Topics:

More PHP Array Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.