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, parameters, and three practical examples that demonstrate value searching, strict type checking, and retrieving keys, helping developers improve array handling efficiency and code readability.

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

In PHP development, we often need to process and modify arrays, and the in_array() function is one of the most commonly used functions for handling arrays. This article introduces how to use this function.

The in_array() function searches for a specified value in an array, returning true if found and false otherwise. Its syntax is as follows:

in_array($value, $array, $strict)

Where $value is the value to search for, $array is the array being searched, and $strict is an optional parameter that determines whether to enforce type checking. By default, $strict is false , meaning only value equality is checked, not type.

Below are some 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 will output "3 exists in the array".

2. Check if a value exists in an array and enforce 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 will output "3 does not exist in the array", because strict type checking makes the string "3" not equal to the integer 3.

3. Find the key name associated with a specified value in an 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 will output "The key for 35 is: Peter", because the key "Peter" corresponds to the value 35.

Summary:

Above is the usage introduction and examples of the in_array() function, hoping to help you in PHP development. The function is frequently used in practice and can effectively improve code efficiency and readability.

PHP8 Video Tutorial

Scan QR code to receive free learning materials

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