PHP Version
4.0.5+
PHP
// Example 1: Using array_search() with a simple array
$arr = ['a', 'b', 'c'];

$key = array_search('c', $arr);
var_dump($key); // Output: int(2)

$notFound = array_search('d', $arr);
var_dump($notFound); // Output: bool(false)


// Example 2: Using array_search() with an associative array
$fruits = [
    'apple' => 'red',
    'banana' => 'yellow',
    'cherry' => 'red'
];

$colorToFind = array_search('red', $fruits);
var_dump($colorToFind); // Output: string(5) "apple"
array_search(mixed $needle, array $haystack, bool $strict = false): int|string|false
$fruits = [
    'apple' => 'red',
    'banana' => 'yellow',
    'cherry' => 'red'
];

// Searches for the value 'red' in the $fruits array and returns the key (or index) of the first match
$colorToFind = array_search('red', $fruits);

// There are two keys with the value 'red' in the $fruits array: 'apple' and 'cherry'.
// $colorToFind is assigned the key of the first matching value ('red').
// Therefore, $colorToFind will be 'apple'.
var_dump($colorToFind); // Output: string(5) 'apple'
$numbers = [0, "0", false, null];
$searchValue = 0;

$result = array_search($searchValue, $numbers, true);

if ($result == false) {
    echo "The value $searchValue was not found in the array.";
} else {
    echo "The value $searchValue is located at index $result.";
}

// Incorrect result!!!
// Output: 'The value 0 was not found in the array.'

if ($result === false) {
    echo "The value $searchValue was not found in the array.";
} else {
    echo "The value $searchValue is located at index $result.";
}

// Output: 'The value 0 is located at index 0.'
$numbers = [1, 2, 3, 4, 2, 5, 6];
$searchValue = 2;

if (array_search($searchValue, $numbers) !== false) {
    echo 'The value exists in the array.';
} else {
    echo 'The value does not exist in the array.';
}

// Output: 'The value exists in the array.'
$products = [
    'apple' => 1.99,
    'banana' => 0.99,
    'cherry' => 2.49
];

$targetPrice = 1.00; // Price to search for

$key = array_search($targetPrice, $products);

if ($key !== false) {
    unset($products[$key]); // Remove the found value
    // Or modify the value: $products[$key] = new price;
} else {
    echo 'Product or price not found.';
}
$students = [
    ['name' => 'Alice', 'age' => 20],
    ['name' => 'Bob', 'age' => 22],
    ['name' => 'Charlie', 'age' => 21]
];

$searchName = 'Bob';

foreach ($students as $key => $student) {
    if (array_search($searchName, $student) !== false) {
        echo "Found student named $searchName. Student index: $key";
        break;
    }
}

// Output: 'Found student named Bob. Student index: 1'
$numbers = [3, 5, 2, 8, 10, 6];
$searchValue = 8;

$key = array_search($searchValue, $numbers);

if ($key !== false) {
    echo "The value $searchValue is located at index $key.";
} else {
    echo "The value $searchValue does not exist in the array.";
}

// Output: 'The value 8 is located at index 3.'