In PHP, you can implement various search algorithms depending on your specific requirements and the data structures you're working with. Below, I'll provide examples of how to implement two common search algorithms: linear search and binary search.
Linear Search:A linear search, also known as sequential search, checks each element in a list one by one until a match is found or the end of the list is reached. Here's a simple PHP implementation of linear search:
function linearSearch($arr, $target) {
$n = count($arr);
for ($i = 0; $i < $n; $i++) {
if ($arr[$i] == $target) {
return $i; // Return the index of the target if found
}
}
return -1; // Return -1 if the target is not found
}
// Example usage:
$myArray = [3, 7, 1, 9, 2, 5];
$targetValue = 9;
$result = linearSearch($myArray, $targetValue);
if ($result != -1) {
echo "Element found at index: " . $result;
} else {
echo "Element not found";
}
Binary Search:
Binary search is an efficient search algorithm that works on sorted arrays. It repeatedly divides the search range in half until the target element is found. Here's how you can implement binary search in PHP:
function binarySearch($arr, $target) {
$left = 0;
$right = count($arr) - 1;
while ($left <= $right) {
$mid = floor(($left + $right) / 2);
if ($arr[$mid] == $target) {
return $mid; // Return the index of the target if found
}
if ($arr[$mid] < $target) {
$left = $mid + 1;
} else {
$right = $mid - 1;
}
}
return -1; // Return -1 if the target is not found
}
// Example usage (array must be sorted):
$myArray = [1, 2, 3, 5, 7, 9];
$targetValue = 5;
$result = binarySearch($myArray, $targetValue);
if ($result != -1) {
echo "Element found at index: " . $result;
} else {
echo "Element not found";
}