PHP in_array() Function With Practical Examples

The built-in PHP in_array() function is used to determine whether a value exists in an array or not.
Depending on the search results, it gives a Boolean value (true or false). This PHP function search array to find the value in the array. If you want to know more about how to search array in PHP, we provided an article about it.

You can use this single function to check if a value exists rather than writing a for loop or foreach loop.
When you don’t need to conduct any more operations to the array, it’s fantastic because it makes your code more compact.

In this article, we will see how to find the value in the array using the in_array() function in PHP.

in_array(value, array, type);

The in_array() function accepts 3 parameters, out of which 2 are compulsory and another 1 is optional.

The value you wish to look for in the array is specified by the value parameter. The array you want to search is the array argument. When looking for a value in the array, the type parameter, which is an optional argument, determines the type of comparison to be used.

The PHP in_array() function is case-sensitive. This means that if you are searching for a string, “Honar” and “honar” are considered two different values. In fact, if the search parameter is a string and the type parameter is set to TRUE, the search is case-sensitive.

The in_array() function can be used to check if a value exists in an array of integers, strings, or objects. If the value is found in the array, the in_array() function will return true. If the value is not found in the array, the in_array() function will return false.

$cars = array(
    'Ferrari', 
    'Benz', 
    'BMW', 
    'Volvo'
);

var_dump(in_array('Benz', $cars));

Output

true

In the example above, the in_array() function will return true since “Benz” is found in the array. The in_array() function in PHP can be used to check if a value exists in an array of associative arrays.

$cars = array(
    'fer' => 'Ferrari', 
    'ben' => 'Benz', 
    'bmw' => 'BMW', 
    'vol' => 'Volvo'
);

var_dump(in_array('Benz', $cars));

Output

true

In the example above, the PHP in_array() function will return true since “Benz” is found in the array.

Shopping Cart