DEV Community

Sharmin Shanta
Sharmin Shanta

Posted on

Linear Search in PHP

The easiest DSA algorithm (Data Structure and Algorithm) is Linear Search. It's simple to implement and doesn't require the data to be in any specific order.

Algorithm:
a. Loop that goes through the array from start to end.
b. Compares the current value with the target value, and returns the current index if the target value is found.
c. End of the loop, return -1, cause of not finding the target value.

Code Example:

/**
 * Linear Search: The Linear Search algorithm searches through an array and returns the index of the value it searches for.
 * It starts from the first element of the array
 *
 * @param array $arr
 * @param int $targetVal
 * @return int
 */
function linearSearch(array $arr, int $targetVal): int
{
    for ($i = 0; $i < count($arr); $i++) {
        if ($arr[$i] == $targetVal) {
            return $i;
        }
    }

    return -1;
}

$arr = [2, 7, 9, 30, 5];
print_r(linearSearch($arr, 5)); // output: 4
Enter fullscreen mode Exit fullscreen mode

Top comments (0)