DEV Community

Youn
Youn

Posted on

PHP in_array() Function – Check if a Value Exists in an Array

😄 This post is based on the content from coding.courses.

(PHP Version | 4+)

Definition and Usage

The in_array() function checks if a specific value exists in an array.

If the specified value is found, the function returns true. Otherwise, it returns false.

This function is commonly used to verify if an input value is contained in a particular array, which helps with validation.

Basic Example

$fruits = ['Apple', 'Orange', 'Banana', 'Grapes'];

if (in_array('Banana', $fruits)) {
    echo 'Banana was found in the array!';
} else {
    echo 'Banana was not found in the array.';
}

// Output: 'Banana was found in the array!'
Enter fullscreen mode Exit fullscreen mode

In the example above, the in_array() function searches the $fruits array for the value 'Banana'. Since it exists in the array, the function returns true, and the message "Banana was found in the array!" is displayed.

Syntax

in_array(mixed $needle, array $haystack[, bool $strict = false]): bool
Enter fullscreen mode Exit fullscreen mode

Parameters

$needle

Required. The value to search for within the array.

$haystack

Required. The array in which the search is performed.

$strict

Optional. If set to true, the search uses strict type comparison, meaning the type of $needle must exactly match the type of the values in the array. If set to false (default), only the value is compared.
When $strict is set:

  • to false, the number 2 and the string '2' are considered equal.
  • to true, the number 2 and the string '2' are considered different.

Return Values

Returns true if the searched value exists in the array; otherwise, returns false.

Practical Examples

# Checking Multiple Values Using a Loop

Since in_array() checks for a single value at a time, you can combine it with a foreach loop to check for multiple values within an array.

$fruits = ['apple', 'orange', 'banana', 'grape'];
$search_values = ['banana', 'grape', 'watermelon']; // List of values to search for

foreach ($search_values as $value) {
    if (in_array($value, $fruits)) {
        echo "Found '{$value}' in the array!" . '<br>';
    } else {
        echo "Did not find '{$value}' in the array." . '<br>';
    }
}
Enter fullscreen mode Exit fullscreen mode
Output:
Found 'banana' in the array!
Found 'grape' in the array!
Did not find 'watermelon' in the array.
Enter fullscreen mode Exit fullscreen mode

# Checking for Value Existence

You can use in_array() to check if a specific value exists in an array. For example, the code below checks whether a user's selected language is supported:

$supported_languages = ['en', 'es', 'fr', 'de'];

$user_language = 'fr';

if (in_array($user_language, $supported_languages)) {
    echo "The selected language '{$user_language}' is supported!";
} else {
    echo "The selected language '{$user_language}' is not supported. Using default language.";
}
Enter fullscreen mode Exit fullscreen mode
Output:
The selected language 'fr' is supported!
Enter fullscreen mode Exit fullscreen mode

# Removing Duplicate Values

You can use in_array() with a foreach loop to filter out duplicate values from an array. This is useful when you want to clean up data or ensure uniqueness in user input.

$numbers = [1, 2, 2, 3, 4, 4, 5];
$unique_numbers = [];

foreach ($numbers as $number) {
    if (!in_array($number, $unique_numbers)) {
        $unique_numbers[] = $number;
    }
}

print_r($unique_numbers);
Enter fullscreen mode Exit fullscreen mode
Output:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
Enter fullscreen mode Exit fullscreen mode

In the example above, we removed duplicate values from the $numbers array and stored only unique ones in the $unique_numbers array. This was done using a foreach loop with in_array(), which checks if a value already exists in the new array before adding it. As a result, $unique_numbers contains only distinct values.

# Validating Input Against Allowed Values

in_array() is commonly used to validate whether an input value belongs to a predefined set of allowed values.

$valid_colors = ['red', 'green', 'blue', 'yellow'];
$user_color = 'orange';

if (in_array($user_color, $valid_colors)) {
    echo 'The selected color is valid!';
} else {
    echo 'The selected color is not allowed.';
}
Enter fullscreen mode Exit fullscreen mode
Output:
The selected color is not allowed.
Enter fullscreen mode Exit fullscreen mode

# Conditional Behavior Based on Value Existence

in_array() is also helpful when you want to perform different actions based on whether a value exists in an array.

$fruits = ['apple', 'orange', 'banana', 'grape'];

if (in_array('orange', $fruits)) {
    echo 'Orange found! Make some orange juice!';
} else {
    echo 'No orange found. Time to buy some!';
}
Enter fullscreen mode Exit fullscreen mode
Output:
Orange found! Make some orange juice!
Enter fullscreen mode Exit fullscreen mode

As you can see, in_array() is a simple yet powerful tool for checking value existence, making it ideal for data validation and conditional logic in everyday programming.

References

PHP in_array() Function – Check if a Value Exists in an Array - codingCourses

The in_array() function checks if a specific value exists in an array. It returns true if the value is found, or false otherwise.

favicon coding.courses

Top comments (0)