How to Use PHP in_array() Function

How to use PHP In_array() function

The PHP in_array() function is a powerful tool in PHP that allows you to check if a specific value exists in an array. This function is handy when you need to validate input, filter data, or implement search functionality in your PHP applications.

It’s a simple function, but it has a few nuances that can drive you crazy until you figure them out. Let’s go over everything.

Syntax and Parameters

The basic syntax of the in_array() function is as follows:

PHP
bool in_array ( mixed $needle , array $haystack [, bool $strict = false ] )

Let’s break down the parameters:

  1. $needle: The value to search for in the array.
  2. $haystack: The array to search in.
  3. $strict (optional): If set to true, the function will also check for type equality.

The function returns true if the $needle is found in the $haystack, and false otherwise.

Basic Usage

Here’s a simple example of how to use in_array():

PHP
$fruits = array("apple", "banana", "orange");
if (in_array("banana", $fruits)) {
    echo "Found banana!";
} else {
    echo "Banana not found.";
}

In this example, the output will be “Found banana!” because “banana” exists in the $fruits array.

Strict Mode

The third parameter, $strict, is particularly important when dealing with different data types. When set to true, it performs a strict comparison (===) instead of a loose comparison (==).

Consider this example:

PHP
$numbers = array(1, "2", 3);

var_dump(in_array(2, $numbers));        // Output: bool(true)
var_dump(in_array(2, $numbers, true));  // Output: bool(false)

In the first case, in_array() returns true because it finds the string “2”, which is loosely equal to the integer 2. In the second case, with strict mode enabled, it returns false because there is no integer 2 in the array.

This Gave Me Trouble

A Software Developer who can't figure out why the PHP In_array function isn't working for him

I couldn’t figure out why some searches worked, while others did not.

This works:

PHP
// single level array
$array = array(5) {
	["keywords"]=> string(5) "74.51"
	["wordCount"]=> string(1) "0"
	["linkCount"]=> string(1) "0"
	["headingCount"]=> string(1) "0"
	["mediaCount"]=> string(1) "0" }
 }
$test_result = in_array(74.51, $array) // test_result is true

This does not until you reference the sub-array (in $test_result2):

PHP
// an array exists within another array
$array = array(6) {
	["width"]=> int(30)
	["height"]=> int(30)
	["file"]=> string(31) "2022/08/icon_mountainbiking.png"
	["filesize"]=> int(1670)
	["sizes"]=> array(0) { }
	["image_meta"]=> array(12) {
		["aperture"]=> string(1) "0"
		["credit"]=> string(0) ""
		["camera"]=> string(0) ""
		["caption"]=> string(0) ""
		["created_timestamp"]=> string(1) "0"
		["copyright"]=> string(0) ""
		["focal_length"]=> string(1) "0"
		["iso"]=> string(1) "0"
		["shutter_speed"]=> string(1) "0"
		["title"]=> string(0) ""
		["orientation"]=> string(1) "0"
		["keywords"]=> array(0) { }
	}
}
$test_result = in_array(0, $array) //test_result is "false"
$test_result2 = in_array(0, $array['image_meta']) //test_result is "true"

Findings:

You must reference the element that contains the array you want to search. You cannot reference the top-level array only and expect it to traverse down through sub-arrays.

The in_array() function alone does not recurse through multidimensional arrays.

The command searches a single-level only.

Searching in Multidimensional Arrays

While in_array() works great for one-dimensional arrays, it doesn’t directly search nested arrays. To search in multidimensional arrays, you’ll need to use it in combination with other functions or write a custom function.

Here’s an example of how you might search a multidimensional array:

PHP
function in_array_r($needle, $haystack, $strict = false) {
    foreach ($haystack as $item) {
        if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
            return true;
        }
    }
    return false;
}

$users = array(
    array("name" => "John", "age" => 25),
    array("name" => "Jane", "age" => 30)
);

var_dump(in_array_r("Jane", $users));  // Output: bool(true)

Performance Considerations

While in_array() is convenient, it can be slower for large arrays because it performs a linear search. For better performance with large datasets, consider using array_flip() in combination with isset():

PHP
$fruits = array("apple", "banana", "orange");
$flipped = array_flip($fruits);

if (isset($flipped["banana"])) {
    echo "Found banana!";
}

This method is generally faster for large arrays because isset() has constant time complexity.

Common Use Cases

  1. Input Validation: Check if a user’s input is in a list of allowed values.
  2. Filtering Data: Remove or keep elements based on whether they exist in another array.
  3. Menu Highlighting: Determine if the current page is in the list of menu items.
  4. Permission Checking: Verify if a user has a specific permission from a list.

Conclusion

The in_array() function is a versatile tool in PHP for checking the existence of values in arrays. Unfortunately, I’ve spent many hours trying to debug an in_array() command and wondering why it wasn’t finding a value that was in a sub-array. Seems simple, but it’s easy to forget.

Remember to consider performance implications for large datasets and explore alternative methods when dealing with multidimensional arrays.

As with any PHP function, it’s always a good idea to refer to the official PHP documentation for the most up-to-date information and additional details about in_array() and related functions.

Happy coding!

P.S. Read this if you want to set up your own PHP server in AWS.

Similar Posts