How to Check if a String exists in an Array in PHP

Checking if a string exists within an array is a common task in PHP. In this post, we’ll explore two methods to achieve this: using the in_array() function and the array_search() function.

Method 1: Using in_array()

The in_array() function checks if a value exists in an array and returns true or false.

 $array = array('apple', 'banana', 'orange'); $searchString = 'banana'; if (in_array($searchString, $array)) { echo 'String found!'; } else { echo 'String not found.'; } 
In this example, in_array() returns true since “banana” is in the array.

Method 2: Using array_search()

The array_search() function searches for a value in an array and returns the index if found, or false if the value is not present.

 $array = array('apple', 'banana', 'orange'); $searchString = 'orange'; $result = array_search($searchString, $array); if ($result !== false) { echo "String found at index: " . $result; } else { echo 'String not found.'; } 
Here, array_search() finds “orange” at index 2.

Final Thoughts
Both in_array() and array_search() are efficient ways to determine if a string exists within an array. Use in_array() if you only need a boolean check, and array_search() if you need the index of the found string.

Leave a Comment