NetBeans PHP Tutorial – Linear Search #14

 

In this tutorial I show how to implement a linear search algorithm in PHP.

 

The code used for this tutorial can be seen here:

<?php
 
$myArray = ["orange", "lemon", "pear", "apple", "lime"];
 
print(linearSearch($myArray, "kiwi"));
 
function linearSearch($array, $toFind) {
	foreach ($array as $key=>$val) {
		if ($val == $toFind) {
			return $key;
		}
	}
	return -1;
}
 
?>

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Name *

This site uses Akismet to reduce spam. Learn how your comment data is processed.