PHP provides powerful built-in array functions that help developers efficiently search and validate data inside arrays.
in_array() checks whether a value exists in an array.array_search() searches for a value and returns its corresponding key.in_array() returns a boolean result.array_search() returns the array index or key.
// Checks if a value exists in an array
in_array($value, $array);
// Returns the key of a value if found
array_search($value, $array);
// Define an array of fruits
$fruits = array("Apple", "Banana", "Cherry");
// Check if Banana exists
echo in_array("Banana", $fruits);
// Check if Orange exists
echo in_array("Orange", $fruits);
The function returns true when "Banana" is found. For "Orange", it returns false since it does not exist in the array.
// Define an array of fruits
$fruits = array("Apple", "Banana", "Cherry");
// Find the index of Banana
echo array_search("Banana", $fruits);
// Try to find Orange
echo array_search("Orange", $fruits);
"Banana" is located at index 1, so that value is returned. When the value is missing, the function returns false.
// Simulating PHP array search logic in JavaScript
const fruits = ["Apple", "Banana", "Cherry"];
// Check existence
console.log(fruits.includes("Banana"));
// Find index
console.log(fruits.indexOf("Banana"));
in_array() for simple existence checks.array_search() when the key/index is required.false.in_array().