How to search value in an Array using PHP

Sometimes in the array, we have to check if the value is present in the array or not. For example, we have input as a variable and we need to check if that variable exists in the array present in the existing array.

For that what we can count the array length and then using for loop we can search value in an Array.

We can also use Regular expression and == operator to compare the two values. In that case if we found the match at that very time we stops the loop and print or can performe some other activity on getting matched value.

When we work in the project, we have to do multiple works with the help of an array. Array is very important in any programming language. Today we are going to check How to search value in an array using PHP.

Let’s suppose we have an array and we want to check if a particular value exists in the array or not. For that PHP provides in_array() function which searches the given value in the array.

The in_array() function is an inbuilt function in PHP. The in_array() function is used to check whether a given value exists in an array or not.

<?php
$array = array('item1', 'item2', 'item3', 'item4');

if (in_array('item3', $array)) {
    echo 'this array contains search value';
}

?>

In the above example, we can see, we pass the first parameter as search value and the second parameter as an array in which we need to search the first parameters. If we found the value in_array() function returns the true otherwise false.

NOTE: The in_array() function returns a boolean value i.e, TRUE if the value is found in the array otherwise it returns FALSE.

Conclusion:

in_array() function is very easy to use, We only need to pass two parameters first one is the value which we want to search and the second value in which we are going the search the first value. It is a very useful function in the PHP and most of the time is used in the projects.

You can also check How to check if a variable is an array in PHP?