Check if a Value Exists in an Array – PHP

How to check if a value exists in an array using PHP. PHP provides a couple of inbuilt method such as in_array() , array_search() through which we can check if a value exists in an array or not. Apart from using inbuilt PHP methods, we’ll write our own custom method as well.

Let’s check how to solve this problem using PHP inbuilt method as well as our own custom function.

Check If  a Value Exist in an Array using PHP –  in_array() Method

PHP in_array() function check if a value exists in an array, return true if it 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.

2. Take a case of an associative array.

We have checked in_array() method for a simple array. Similarly, it works for an associative array as well.

How to return multiple values from a function in PHP

Subscribe Our Tutorials

Get Latest Updates on Facebook

Using array_search() method to check if value exists in array

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). Similar to triple equal to.

Custom Function to check if a value exists in an array

So we have checked PHP inbuilt functions. 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.

Linear Search Algorithm.


I have explained all the methods which i used to check if a value exists in an array. If you know any other method then you can let us know through your comments.


About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.
Tagged , . Bookmark the permalink.