DEV Community

Sharmin Shanta
Sharmin Shanta

Posted on

1

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

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay