Implementation of Linear Search in PHP
Linear search, also known as sequential search, is a basic method for finding a specific element in an array. In this article, we will explore the implementation of linear search in PHP.
Basic Linear Search
The basic idea of linear search is to iterate through the array and compare each element with the target value until a match is found or the end of the array is reached.
PHP
<?php function linearSearch( $arr , $target ) { $length = count ( $arr ); for ( $i = 0; $i < $length ; $i ++) { if ( $arr [ $i ] == $target ) { // Return index of target element return $i ; } } // Return -1 if target element // is not found return -1; } // Driver code $arr = [10, 20, 30, 40, 50]; $targetValue = 30; $result = linearSearch( $arr , $targetValue ); if ( $result != -1) { echo "Element found at index $result" ; } else { echo "Element not found in the array" ; } ?> |
Output
Element found at index 2
Linear Search with Enhanced Features
You can enhance the basic linear search implementation by adding features such as counting occurrences, returning multiple indices, or handling different data types.
PHP
<?php function linearSearch( $arr , $target , $occurrences = false) { $length = count ( $arr ); $indices = []; for ( $i = 0; $i < $length ; $i ++) { if ( $arr [ $i ] == $target ) { $indices [] = $i ; if (! $countOccurrences ) { return $indices ; } } } return $occurrences ? count ( $indices ) : $indices ; } // Driver code $arr = [10, 20, 30, 40, 50]; $targetValue = 30; $result = linearSearch( $arr , $targetValue ); if ( is_array ( $result )) { echo "Element found at index " . implode( ', ' , $result ); } else { echo "Element not found in the array" ; } ?> |
Output
Element found at index 2