Backend Development 4 min read

Using PHP in_array() Function: Syntax, Parameters, and Practical Examples

This article explains the PHP in_array() function, detailing its syntax, optional strict mode parameter, and provides three clear code examples that demonstrate checking for values, enforcing type comparison, and retrieving keys associated with specific values in arrays.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP in_array() Function: Syntax, Parameters, and Practical Examples

In PHP development, handling and modifying arrays is common, and the in_array() function is one of the most frequently used tools for array processing. This article introduces how to use this function.

The in_array() function searches for a specified value within an array, returning true if the value is found and false otherwise. Its syntax is shown below:

in_array($value, $array, $strict)

Where $value is the value to search for, $array is the array being searched, and $strict is an optional boolean that determines whether to enforce strict type checking. By default, $strict is false , meaning only the values are compared without considering their types.

Below are several usage examples of in_array() :

1. Check whether a value exists in an array

$numbers = array(1, 2, 3, 4, 5);
if (in_array(3, $numbers)) {
    echo "3 exists in the array";
} else {
    echo "3 does not exist in the array";
}

The above code outputs "3 exists in the array".

2. Check whether a value exists with strict type comparison

$numbers = array(1, 2, 3, 4, 5);
if (in_array("3", $numbers, true)) {
    echo "3 exists in the array";
} else {
    echo "3 does not exist in the array";
}

This code outputs "3 does not exist in the array" because strict type checking treats the string "3" and the integer 3 as different.

3. Find the key name associated with a specific value in an associative array

$ages = array("Peter" => 35, "Ben" => 28, "Joe" => 40);
if (in_array(35, $ages)) {
    echo "The key for 35 is: " . array_search(35, $ages);
} else {
    echo "35 does not exist in the array";
}

The above code outputs "The key for 35 is: Peter" because the value 35 is associated with the key "Peter".

Summary:

The in_array() function is a highly useful PHP built‑in for checking the presence of values in arrays, optionally enforcing strict type comparison, and can be combined with array_search() to retrieve corresponding keys, making it essential for efficient backend development.

BackendProgrammingPHParrayin_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.