PHP

PHP in_array Function

The in_array() function in PHP checks if a value exists in an array. It returns true if the value is found, false if not. The function is case-sensitive, distinguishing between uppercase and lowercase characters.

Basic syntax of in_array() function:

bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )
Parameter Description
$needle The value to search for in the array.
$haystack The array in which to search for the value.
$strict [optional] - If set to true, the function will also check for the same type of the given value. By default, it is set to false.

Search a string in an array of strings:

$array = [1, 2, 'search'];

in_array('search', $array); // true
in_array('missing', $array); // false

Search an integer in an array: The third parameter true will check for the type of your input:

$array = [1, 2, '3'];

in_array(3, $array, true); // false
in_array('3', $array, true); // true

First lets convert an array to a collection:

$array = ['apple', 'banana', 'orange'];
$collection = collect($array);

Now you can use the contains method to search your array:

$collection->contains('banana'); // true

Read more about collections in my Laravel Collection Tips and Tricks article.

Add this to your AppServiceProvider:

Arr::macro('contains', function($array, $needle) {
		return in_array(
			$needle, $array instanceof Collection
				? $array->flatten()->toArray()
				: static::flatten($array)
		);
});

Now you can use it like so:

Arr::contains('search', $array);