Check if String is in Array in PHP

This tutorial will discuss about unique ways to check if string is in array in php.

Table Of Contents

Method 1: Using in_array()

Suppose you have an array of strings, now we want to check if this array contains a specific string or not.

For that we can use the in_array() function in PHP.

It accepts a string value as the first argument and an array as the second argument and returns true if the given string value exists in the array.

Let’s see the complete example,

<?php
$arr = ['Why', 'What', 'Where', 'How'];
$strValue = 'Where';

// Check if the string is present in
// the array using in_array()
if (in_array($strValue, $arr)) {
    echo "The string is present in the array.";
} else {
    echo "The string is not present in the array.";
}
?>

Output

The string is present in the array.

The PHP provides a function array_search() which accepts a string as the first argument and array as the second argument. Then it looks for the given string in the array and if array contains the string then it returns the first corresponding key for that string. Where as, if it does not exist in array then it returns false.

If it is a one dimensional array, then it returns the index position of the given string in the array.

So, if array_search() does not return false, it means array contains the given string value.

Let’s see the complete example,

<?php
$arr = ['Why', 'What', 'Where', 'How'];
$strValue = 'Where';

// Check if the string is present in the
// array using array_search()
if (array_search($strValue, $arr) !== false) {
    echo "The string is present in the array.";
} else {
    echo "The string is not present in the array.";
}
?>

Output

The string is present in the array.

Summary

We learned about two different ways to Check if String is in Array in PHP.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top