Backend Development 4 min read

Understanding and Using PHP's in_array() Function

This article explains the PHP in_array() function, covering its syntax, basic usage, checking multiple values, strict type comparison, and a simple permission‑control example, providing clear code samples to help developers efficiently determine whether a value exists in an array.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Understanding and Using PHP's in_array() Function

PHP provides many useful functions, and in_array() is one of the most common for checking whether a specific value exists within an array.

The function signature is in_array($needle, $haystack, $strict) , where $needle is the value to search for, $haystack is the array being searched, and the optional $strict parameter enforces type‑strict comparison when set to true .

Basic usage returns true if the value is found and false otherwise, as shown in the following example:

$arr1 = array("apple", "banana", "orange");
echo in_array("apple", $arr1); // true
echo in_array("lemon", $arr1); // false

To check multiple values, you can loop over a list of search items and call in_array() for each, for example:

$names = array("Alice", "Bob", "Charlie", "Dave", "Eve");
$search = array("Alice", "John");
foreach ($search as $name) {
    if (in_array($name, $names)) {
        echo "$name exists in names.";
    } else {
        echo "$name does not exist in names.";
    }
}

When strict mode is enabled ( $strict = true ), the function also compares the type of the needle with the array elements, preventing values like the string "1" from matching the integer 1:

$numbers = array("1", 2, 3);
echo in_array(1, $numbers);            // true (non‑strict)
echo in_array(1, $numbers, true);      // false (strict)

A practical application is simple permission control, where a user's role is checked against an allowed‑roles array:

$user_role = "manager";
$allowed_roles = array("manager", "admin", "superadmin");
if (in_array($user_role, $allowed_roles)) {
    // access granted
} else {
    // access denied
}

In summary, in_array() is a versatile PHP function that can quickly determine the presence of a value in an array, and with optional strict mode or looping logic, it supports more complex scenarios such as multi‑value checks and basic access control.

Backendphp-functionsarray-searchin_array
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.