PHP in_array() Function (original) (raw)

Last Updated : 02 Jun, 2025

The in_array() function in PHP is a built-in function that is used to check if a specific value exists within an array and returns a boolean result. Returns true if the value is found and false if the value is not found.

Syntax:

bool in_array(mixed needle,arrayneedle, array needle,arrayhaystack, bool $strict = false)

**In this syntax:

Return Value

How in_array() Works?

The in_array() function in the PHP works in the following ways:

**Now, let us understand with the help of the example:

PHP `

`

Output

Banana is in the list!

1. Using in_array() with Numbers

This example demonstrates how in_array() checks for both numeric and string values in an array using loose comparison.

PHP `

`

Output

bool(true) bool(true) bool(false)

2. Strict Type Checking

This example illustrates how in_array() uses strict mode to compare both value and type when searching in an array.

PHP `

`

Output

bool(false) bool(true)

3. Case Sensitivity

This example highlights in_array()’s case-sensitive behavior when searching for string values inside an array.

PHP `

`

Output

bool(false) bool(true)

4. Searching in Multidimensional Arrays

in_array() does not search inside nested arrays automatically:

PHP `

1, "name" => "anjali"], ["id" => 2, "name" => "arti"] ]; var_dump(in_array("anjali", $array)); ?>

`

To search deeply in multidimensional arrays, you need to use custom functions or array functions like array_column():

PHP `

names=arraycolumn(names = array_column(names=arraycolumn(array, 'name'); if (in_array("anjali", $names)) { echo "anjali is found!"; } } else { echo "Input data is not valid."; } ?>

`

Output

Input data is not valid.

Common Use Cases for in_array()

Best Practices

Conclusion

The PHP in_array() function is a straightforward and handy tool for checking if a value exists within an array. Its flexibility with the optional strict type checking and compatibility with various data types make it a staple in PHP programming. Remember its limitations in multidimensional arrays and case sensitivity to use it effectively.