Backend Development 5 min read

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

This tutorial explains the PHP in_array() function, detailing its syntax, parameter meanings—including optional strict type checking—and provides three practical code examples demonstrating basic existence checks, strict type comparisons, and searching associative arrays to retrieve corresponding keys.

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

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

The in_array() function searches for a specified value in an array and returns true if found, otherwise false . 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 type checking. By default $strict is false , meaning only value equality is checked, not type.

Below are several usage examples of in_array() :

1. Check if 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 if a value exists in an array with strict type checking

$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";
}

The above code outputs “3 does not exist in the array”, because strict type checking makes the string “3” not equal to the integer 3.

3. Find whether a value exists in an associative array and retrieve its key name

$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 key “Peter” corresponds to the value 35.

Summary:

The above demonstrates the usage and examples of the in_array() function, which is widely used in PHP development and can effectively improve code efficiency and readability.

Java learning material download

C language learning material download

Front-end learning material download

C++ learning material download

PHP learning material download

Backend DevelopmentPHPcode examplesarray-functionsin_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.