The following function searches for an element $x from an array called $arr by going through each element of the array, one by one. If the element is found in the array, the function returns the index of the element, otherwise, it returns -1.

Linear Search function using PHP

<?php
    function search($arr, $x) {
        for($i = 0; $i < sizeof($arr); $i++) {
            if($arr[$i] == $x) return $i;
        }
        return -1;
    }
    $arr = array(4, 2, 5, 6, 14, 7, 15, 3);
    echo search($arr, 14);
    
  
?>

More PHP Snippets

 

Last modified: November 4, 2019

Comments

Write a Reply or Comment

Your email address will not be published.