PHP

Check if an Array Contains a Value (Case-Insensitive Search)

Learn to robustly check if a specific value exists within a PHP array, including performing a case-insensitive search, and retrieving the key of the found element.

<?php

$fruits = ['Apple', 'Banana', 'Orange', 'Grape'];

// 1. Basic case-sensitive check
$search1 = 'Banana';
if (in_array($search1, $fruits)) {
    echo "'{$search1}' found in array (case-sensitive).
";
} else {
    echo "'{$search1}' not found in array (case-sensitive).
";
}

// 2. Case-insensitive check using array_map and in_array
$search2 = 'banana';
$fruits_lower = array_map('strtolower', $fruits);
if (in_array(strtolower($search2), $fruits_lower)) {
    echo "'{$search2}' found in array (case-insensitive).
";
} else {
    echo "'{$search2}' not found in array (case-insensitive).
";
}

// 3. Finding the key of a value (case-insensitive)
$search3 = 'orange';
$key_found = array_search(strtolower($search3), $fruits_lower);

if ($key_found !== false) {
    echo "'{$search3}' found at key '{$key_found}' (case-insensitive). The original value is: {$fruits[$key_found]}
";
} else {
    echo "'{$search3}' not found in array (case-insensitive).
";
}

/*
Output:
'Banana' found in array (case-sensitive).
'banana' found in array (case-insensitive).
'orange' found at key '2' (case-insensitive). The original value is: Orange
*/
How it works: This snippet demonstrates how to check for the existence of a value within a PHP array. It covers the basic case-sensitive search using `in_array`. More importantly, it shows a common pattern for performing a case-insensitive search by converting all array elements and the search term to a consistent case (e.g., lowercase) using `array_map` and `strtolower` before using `in_array`. Additionally, it illustrates how `array_search` can be used to not only check for existence but also retrieve the corresponding key of the found element, which is useful when you need to access the original value.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs