array_search Without Built-in PHP Array Functions
Description
This example manually searches for a value in an array and returns its key. If the value is not found, it returns false. The logic uses a foreach loop to iterate through the array.
Code Example
<?php
// Function to search for a value in an array
function customArraySearch($needle, $haystack) {
foreach ($haystack as $key => $value) {
if ($value === $needle) { // Compare values strictly
return $key; // Return the key if found
}
}
return false; // Return false if not found
}
// Test array
$array = ["apple", "banana", "cherry", "date", "elderberry"];
// Value to search for
$searchValue = "cherry";
// Call the custom function
$result = customArraySearch($searchValue, $array);
// Output
if ($result !== false) {
echo "Value '{$searchValue}' found at key: {$result}";
} else {
echo "Value '{$searchValue}' not found in the array.";
}
?>
Output:
Explanation
- Function customArraySearch:
- Accepts two parameters: the value to search (needle) and the array to search in (haystack).
- Iterates through the array using a foreach loop.
- Checks each value with === to ensure strict comparison.
- Returns the key if a match is found.