Skip to content

Commit 624038e

Browse files
committed
Linear Search Code added
1 parent 6d34788 commit 624038e

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
<?php
2+
/* Linear Search implementation in PHP */
3+
function linearSearch(Array $arr, $item) {
4+
foreach ($arr as $val) { //Traversing through the whole array to search for the 'item'
5+
if($val === $item)
6+
return true; //If the item found return true. You can also return the 'index' of the array here instead
7+
}
8+
9+
return false;
10+
}
11+
12+
13+
/************ Testing Linear Search implementation ****************/
14+
$hayStack = array('book', 'pencil', 'pen', 'note book', 'sharpener', 'rubber');
15+
$needle = 'note book';
16+
17+
echo linearSearch($hayStack, 'note book') ? 'True' : 'False';
18+
echo PHP_EOL;
19+
echo linearSearch($hayStack, 'dog') ? 'True' : 'False';
20+
echo PHP_EOL;
21+
22+
?>

0 commit comments

Comments
 (0)