Objective

Create a function to search for a given value in an array.

Difficulty

Very easy

Description

Suppose we have a given array and want to check whether it has a given item in it or not.

This can easily be done by sequentially iterating over the array and comparing each subsequent element with the item to find.

An algorithm that operates in this manner in order to search for a value in a array is generally known as a sequential search, or linear search, algorithm.

The term 'linear' comes from the fact that the running time of this algorithm can be expressed as a linear function on the length of the array.

In this exercise, you have to create a function linear_search() that implements the linear search algorithm in order to search for an item in a given array.

Its general form should be as follows:

function linear_search($arr, $target) {
   // Code here...
}

Two arguments should be provided to the function — the first is the array where to search for the target item, while the second is the item itself.

The function should return true if the target exists in the array, or else false.

Note that the function should search exactly for the target in the array.

Shown below are a couple of examples of the usage of the function:

<?php

function linear_search($arr, $target) { /* ... */ }

var_dump(linear_search([1, 2, 3], 2));
var_dump(linear_search([1, 2, 3], '2'));
var_dump(linear_search(['2', '4', '6'], '2'));
var_dump(linear_search(['2, 6', '1, 4'], '2'));
var_dump(linear_search([false, false, false, true], false));
bool(true) bool(false) bool(true) bool(false) bool(true)