PHP
Check if a Value Exists in a PHP Array
Efficiently determine if a specific value is present in a PHP array using `in_array`, or check for complex conditions using `array_filter` with a callback.
<?php
$fruits = ['apple', 'banana', 'orange'];
// Using in_array for exact match
if (in_array('banana', $fruits)) {
echo "Banana is in the array.
";
} else {
echo "Banana is not in the array.
";
}
if (in_array('grape', $fruits)) {
echo "Grape is in the array.
";
} else {
echo "Grape is not in the array.
";
}
// Checking for a value based on a custom condition
$products = [
['name' => 'Laptop', 'price' => 1200],
['name' => 'Mouse', 'price' => 25],
['name' => 'Keyboard', 'price' => 75],
];
$hasExpensiveProduct = array_filter($products, function($product) {
return $product['price'] > 1000;
});
if (!empty($hasExpensiveProduct)) {
echo "There is at least one expensive product.
";
} else {
echo "No expensive products found.
";
}
?>
How it works: For simple checks to see if a literal value exists in an array, `in_array()` is the most straightforward function. For more complex conditions where you need to evaluate elements based on specific criteria (e.g., checking properties of associative array items), `array_filter()` can be used. If the resulting filtered array is not empty, it signifies that at least one element matched the condition.