PHP Array Search
A search function can return a valid key that is also false-like. Read its return contract before deciding whether the search succeeded.
How it works
array_search returns a matching key or false. Integer key zero is a real successful result, so compare the return value with false strictly. Pass the strict flag when matching should preserve types as well as values. in_array answers a membership question rather than returning a key; array_key_exists checks keys rather than values. Select the API that answers the actual question.
Run it locally
Run this complete source locally with PHP 8.2 or newer. Save it using the filename shown and run the command below. PHP is not currently available in Bhylu’s browser playground. Apache and MySQL are not needed for an ordinary CLI example.
php -l array-search.php
php array-search.phpDownload this source as a local PHP lab file. Keep lab files separate from the Bhylu project and production data.
Example
<?php
declare(strict_types=1);
$items = ["Spade", "Drill", "Rake"];
$key = array_search("Spade", $items, true);
if ($key !== false) { echo "Found at ", $key, "\n"; }
echo in_array("Saw", $items, true) ? "Saw present\n" : "Saw absent\n";
Expected result
Found at 0
Saw absentThe first item is found at key zero. A loose if ($key) would incorrectly treat that successful search as failure. The second operation only asks whether Saw is present, so a boolean is the right contract. A map lookup could be more direct than repeated full-list searches when the program needs frequent lookup by a stable identifier.
Check the official PHP manual for detailed version and API contracts.