Sling Academy
Home/PHP/How to check if an array contains a value in PHP

How to check if an array contains a value in PHP

Last updated: January 10, 2024

Introduction

Working with arrays is fundamental in PHP programming. Often, we find ourselves in situations where we need to check whether a value exists within an array. This check can be done using various functions built into PHP, each with its advantages. This tutorial covers several methods from the simple in_array function to more advanced techniques.

Using in_array()

The in_array() function is the most straightforward way to check if a value exists in an array. It returns true if the value is found in the array and false otherwise. Here is a basic example:

<?php
$array = array('apple', 'banana', 'cherry');
if (in_array('banana', $array)) {
    echo 'Found Banana!';
} else {
    echo 'Banana not found.';
}
?>

Output: Found Banana!

Note: To perform a type-safe check, you can pass a third parameter as true to ensure the type matches, like so:

<?php
$array = array('apple', 1, 'cherry');
if (in_array('1', $array, true)) {
    echo 'String 1 found!';
} else {
    echo 'String 1 not found.';
}
?>

Output: String 1 not found.

Using array_search()

array_search() function searches the array for a given value and returns the corresponding key if a value is found in the array. If the value is not found, it will return false.

<?php
$array = array('apple', 'banana', 'cherry');
$key = array_search('banana', $array);
if ($key !== false) {
    echo 'Key for Banana: ' . $key;
} else {
    echo 'Banana not found.';
}
?>

Output: Key for Banana: 1

Using array_key_exists()

If you are checking the presence of a particular key rather than a value, array_key_exists() function comes into play. It checks if the specified key is present in the array. :

<?php
$array = array('a' => 'apple', 'b' => 'banana', 'c' => 'cherry');
if (array_key_exists('b', $array)) {
    echo 'Key b exists!';
} else {
    echo 'Key b does not exist.';
}
?>

Output: Key b exists!

Using foreach Loop

Sometimes specific search criteria can’t be addressed by built-in functions. In such cases, a foreach loop can be used to iterate through the array and check for the value manually:

<?php
$array = array('apple', 'banana', 'cherry');
$search_value = 'cherry';
$found = false;
foreach ($array as $item) {
    if ($item === $search_value) {
        $found = true;
        break;
    }
}
if ($found) {
    echo 'Cherry found!';
} else {
    echo 'Cherry not found.';
}
?>

Output: Cherry found!

Further Observations and Tips

All mentioned functions work with both numerical and associative arrays. However, understanding when to use each function will improve code efficiency and readability. For instance, use in_array() when you simply need to confirm a value’s existence, and array_search() is when you also need the key.

Performance Considerations

When working with large arrays, performance might be a concern. In such cases, avoid using a foreach loop to perform a simple value check and instead rely on the native PHP functions optimized for such operations.

Conclusion

This tutorial has walked you through the primary techniques of checking values in an array using PHP. Knowing these various methods will arm you with the right tools to tackle array manipulation effectively.

Next Article: PHP: How to split an array into chunks

Previous Article: PHP: Sorting an array of arrays by key

Series: PHP Data Structure Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array