PHP

Checking for a Value in an Array (Case-Insensitive)

Implement a robust method to check if an array contains a specific string value, ignoring case, using a combination of `array_map` and `in_array`.

<?php
$colors = ['Red', 'Green', 'Blue', 'Yellow'];
$searchColor = 'blue';

// Default in_array() is case-sensitive
$isFoundSensitive = in_array($searchColor, $colors);
// $isFoundSensitive is false

// Case-insensitive check using array_map and strtolower
$lowerColors = array_map('strtolower', $colors);
$isFoundInsensitive = in_array(strtolower($searchColor), $lowerColors);
// $isFoundInsensitive is true

// Concise version
$isFoundConcise = in_array(strtolower($searchColor), array_map('strtolower', $colors));
// $isFoundConcise is true

$fruits = ['Apple', 'Orange', 'Grape'];
$checkFruit = 'apple';

if (in_array(strtolower($checkFruit), array_map('strtolower', $fruits))) {
    echo "The fruit '{$checkFruit}' is in the array (case-insensitive).";
} else {
    echo "The fruit '{$checkFruit}' is NOT in the array (case-insensitive).";
}
?>
How it works: PHP's `in_array()` function performs a case-sensitive check by default. To perform a case-insensitive search, you can combine `array_map()` with `strtolower()`. First, `array_map('strtolower', $haystackArray)` transforms all string values in the target array to lowercase. Then, `strtolower($searchValue)` converts the search term to lowercase as well. Finally, `in_array()` is used to compare the lowercase search term against the all-lowercase array, effectively performing a case-insensitive check.

Need help integrating this into your project?

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

Hire DigitalCodeLabs