How to check if a value exists in an array in PHP. In this tutorial, I am going to discuss PHP inbuilt and custom method to check if value exists in array.
PHP provides couple of in-built methods to check whether a value exists in an array or not. Methods such as in_array(), array_search() etc.
Let’s discuss, how we can use these methods as well as we write our own custom method to check if a value exists in an array.
PHP in_array() method to Check If a Value Exists in an Array in PHP
PHP in_array() method check if a value exists in an array, It returns true if a value exists otherwise false.
Syntax –
1. Let’s first take the case of a simple array.
How to check if a value exists in an array using jquery/javascript
Top five most used PHP array functions
PHP : Check if value exists in Associative array
In above example, we have used in_array() method for a simple array. Let’s check in_array() method for an associative array.
How to return multiple values from a function in PHP
PHP array_search() method to check if a value exists in an array in PHP
PHP array_search() method search an array for given value and return the corresponding key if a value exists in an array. If a value doesn’t exist in an array then it returns NULL.
How to sort string using PHP code
Syntax –
if strict is set to true which is false by default, then it searches for an identical element (strict type checking). In PHP, Strict type comparison is done through triple equal to (===).
Difference between double and triple equals to in PHP
PHP Function to check if a value exists in an array
In above example, We have discussed PHP inbuilt functions to check if a value exists in an array. Let’s create our own custom function which takes two arguments ( array and the value to be searched). It compares the value to each element of an array.
Conclusion
I have explained all the methods which I used to check whether a value exists in an array or not. If you know any other method then you can let us know through your comments.