Check if an Array contains a value in PHP

This tutorial will discuss about unique ways to check if an array contains a value in php.

Table Of Contents

Method 1: Using in_array() function

The in_array() function in PHP, accepts a value and an array as arguments, and returns true, if the value exists in the array. So, we can use this to check if an array contains a value or not in PHP.

Let’s see the complete example,

<?php
$arr = array('for', 'why', 'this', 'here', 'some');
$value = 'this';

# Check if Array contains a specific Value
if (in_array($value, $arr)) {
    echo "Yes, Value exists in the array";
}
else {
    echo "No, Value does not exists in the array";
}
?>

Output

Yes, Value exists in the array

As the value exists in the array, therefore it returned the boolean value true.

Method 2: Using array_search() function

The array_search() function in PHP, accepts a value and an array as arguments, and returns the key/index of first occurrence of given value in array. If the value does not exists in the array, then it returns false. So, we can use this to check if an array contains a value or not in PHP.

Let’s see the complete example,

<?php
$arr = array('for', 'why', 'this', 'here', 'some');
$value = 'this';

# Check if Array contains a specific Value
if (array_search($value, $arr) !== false) {
    echo "Yes, Value exists in the array";
}
else {
    echo "No, Value does not exists in the array";
}
?>

Output

Yes, Value exists in the array

As the value exists in the array, therefore it didn’t returned the boolean value false.

Summary

We learned about two different ways to check if a value exists in an 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