← Back to Chapters

PHP in_array() & array_search()

? PHP in_array() & array_search()

? Quick Overview

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.

? Key Concepts

  • Both functions perform a linear search.
  • in_array() returns a boolean result.
  • array_search() returns the array index or key.

⚡ Syntax / Theory

? View Code Example
// Checks if a value exists in an array
in_array($value, $array);

// Returns the key of a value if found
array_search($value, $array);

? Example: Using in_array()

? View Code Example
// 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);

? Explanation

The function returns true when "Banana" is found. For "Orange", it returns false since it does not exist in the array.

? Example: Using array_search()

? View Code Example
// 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);

? Explanation

"Banana" is located at index 1, so that value is returned. When the value is missing, the function returns false.

? Interactive Visualization (JS Simulation)

? View Code Example
// 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"));

? Use Cases

  • Form validation
  • Checking user permissions
  • Filtering allowed values
  • Finding positions inside datasets

✅ Tips & Best Practices

  • Use in_array() for simple existence checks.
  • Use array_search() when the key/index is required.
  • Always compare results strictly with false.

? Try It Yourself

  • Create an array of colors and check if "Red" exists.
  • Search for a product price and display its index.
  • Check employee names using in_array().