Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ For this PHP code exercise, create a file named `string_search.php`. This file s

If *needle* is not found in *haystack*, `string_search()` should return `false`. If *needle* is found in *haystack*, `string_search()` should return string formatted as `Found 'needle' at index x` where `needle` is the first parameter and `x` is the starting index where `needle` was found.

For example, if *needle* were `search` and *haystack* were `string search`, `string_search()` should return `Found 'search' at position 7`.
For example, if *needle* were `search` and *haystack* were `string search`, `string_search()` should return `Found 'search' at index 7`.

There are a few special cases:

Expand Down
34 changes: 34 additions & 0 deletions src/string_search.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php
// For this PHP code exercise, create a file named string_search.php. This file should contain a function named string_search() which accepts two parameters. The first is the string to search for (needle) and the second is the string to search (haystack).

// If needle is not found in haystack, string_search() should return false. If needle is found in haystack, string_search() should return string formatted as Found 'needle' at index x where needle is the first parameter and x is the starting index where needle was found.

// For example, if needle were search and haystack were string search, string_search() should return Found 'search' at position 7.

// There are a few special cases:

// If needle is an empty string, string_search() should return false.
// If needle is found in haystack multiple times, string_search() should return the first index.



// $haystack = 'Elephants are afraid of needles!';
// $needle = 'needle';

function string_search($needle, $haystack) {

if ($needle == '') {
return false;
} else {
$string_search = strpos($haystack, $needle);
if ($string_search !== false) {
return "Found '$needle' at index $string_search";
} else {
return false;
}
}
}

// echo string_search();

?>