Array search functions help you find if a value exists in a list and where it is. This saves time compared to checking each item yourself.
Array search functions in PHP
<?php // Search for a value in an array and get its key $key = array_search(mixed $needle, array $haystack, bool $strict = false); // Check if a value exists in an array $exists = in_array(mixed $needle, array $haystack, bool $strict = false); ?>
array_search returns the key of the found value or false if not found.
in_array returns true if the value exists, otherwise false.
<?php $fruits = ['apple', 'banana', 'cherry']; $key = array_search('banana', $fruits); echo $key; // Outputs 1 ?>
<?php $fruits = ['apple', 'banana', 'cherry']; $exists = in_array('grape', $fruits); echo $exists ? 'Found' : 'Not found'; // Outputs 'Not found' ?>
<?php $emptyArray = []; $key = array_search('anything', $emptyArray); var_dump($key); // Outputs bool(false) ?>
<?php $singleElement = ['only']; $key = array_search('only', $singleElement); echo $key; // Outputs 0 ?>
This program shows how to use array_search and in_array to find values in arrays. It prints the array, searches for values, and handles empty arrays.
<?php // Define an array of colors $colors = ['red', 'green', 'blue', 'yellow']; // Print the original array echo "Original array:\n"; print_r($colors); // Search for 'blue' in the array $searchKey = array_search('blue', $colors); if ($searchKey !== false) { echo "\nFound 'blue' at key: $searchKey\n"; } else { echo "\n'blue' not found in the array.\n"; } // Check if 'purple' exists in the array $exists = in_array('purple', $colors); echo $exists ? "\n'purple' is in the array.\n" : "\n'purple' is not in the array.\n"; // Search for 'red' in an empty array $emptyArray = []; $emptySearch = array_search('red', $emptyArray); echo $emptySearch === false ? "\n'red' not found in empty array.\n" : "\nFound 'red' in empty array.\n"; ?>
Time complexity: Both array_search and in_array check items one by one, so they take time proportional to the array size (O(n)).
Space complexity: These functions do not use extra space beyond a few variables.
A common mistake is to check if (array_search(...) == false) which fails if the found key is 0. Always use strict comparison !== false.
Use array_search when you need the key of the found value. Use in_array when you only need to know if the value exists.
Array search functions help find values or keys in arrays easily.
array_search returns the key or false if not found.
in_array returns true or false depending on presence.