PHP in_array() function is used to check whether a given value exists in an array or not.
PHP in_array
PHP in_array() is a built-in function that checks if the value exists in the array. The in_array() function checks if the search value exists in the array. The search is case-sensitive if the search parameter is the string and the type parameter is set to TRUE.
If the search_value is found, then it returns TRUE. Otherwise, it returns FALSE.
Syntax
in_array(search, array, type)
Parameters
The in_array() function accepts three parameters, out of which two are compulsory, and another one is optional.
The search parameter is required, and it is the value that needs to be searched in an array.
An array parameter is required, and it is the array in which we search the value.
The type parameter is optional, and If this parameter is set to TRUE, the in_array() function searches for the search string and specific type in the array.
Example
See the following example.
<?php // app.php $MVP = ['Arya', 'Jon', 'Sansa', 'Tyrion', 'Bran']; if (in_array('Bran', $MVP)) { echo "Bran has won the Iron Throne"; } else { echo "Nobody has won the Game of Thrones"; }
In the example, we have defined one array called $MVP, and the array has five items.
Next, we check the Bran elements inside the $MVP array using the in_array() function.
The program will print that Bran has won the Iron Throne if it returns true.
The in_array() function in strict mode
Let’s check the function in strict mode. Then, we can pass the third parameter as true and see the outcome.
<?php // app.php $MVP = ['Arya', 'Jon', 'Sansa', 'Tyrion', 'Bran', '19']; if (in_array(19, $MVP, true)) { echo "19 is there"; } else { echo "Datatype is not matching"; }
See the below output.
PHP in_array() function is case-sensitive
Let’s see a scenario where we check the case sensitivity and see the outcome.
<?php // app.php $MVP = ['Arya', 'Jon', 'Sansa', 'Tyrion', 'Bran']; if (in_array('BRAN', $MVP)) { echo "Bran has won the Iron Throne"; } else { echo "Nobody has won the Game of Thrones"; }
See the below output.
Free checking returns some crazy, counter-intuitive results when used with specific arrays. It is entirely correct behavior due to PHP’s leniency on variable types, but in “real life,” it is almost useless.
If you want to know how to check if a value exists in an array in PHP, then the in_array() function is proper.
In_array() has the optional boolean third parameter (set to false by default) that defines whether you want to use the strict checking or not.
If parameter three is set to true, PHP will only return true if a value is in an array and it is of the same type – that is, if they are identical in the same way as the === operator (three equals signs).
This is not used very often, but you must be at least aware of its existence.
That’s it for this tutorial.