Skip to content

Instantly share code, notes, and snippets.

@harmlessprince
Last active April 27, 2021 03:53
Show Gist options
  • Save harmlessprince/25f6bf8b23557c9582a02500043545c6 to your computer and use it in GitHub Desktop.
Save harmlessprince/25f6bf8b23557c9582a02500043545c6 to your computer and use it in GitHub Desktop.
This function returns start and end position of of given value in an array
<?php
function FindStartEnd($array, $val)
{
$type = gettype($array);
try {
if (!$array) {
throw new Exception("Expects parameter 1 to be array and should contain at least one value");
}
if (!is_numeric($val)) {
throw new Exception("Second value passed must be a number");
}
if(sort($array)){
$indexes = array_keys($array, $val);
if (!$indexes) {
return [-1, -1];
}
return [min($indexes), max($indexes)];
}
throw new Exception("expects parameter 1 to be array, $type given");
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage() . "\n";
}
}
print_r(FindStartEnd([0,8,-2,5,0], 0));
@meekg33k
Copy link

Really commendable effort @harmlessprince, I like this solution a lot better even though it is still dependent on the performance of array_keys and count functions.

I have written a blog post here sharing my solution to this problem - a solution that avoids having to sort the array. Please read through and let me know what you think.

Thank you for participating once again and see you on Friday for Week 4 of #AlgorithmFridays.

@harmlessprince
Copy link
Author

Thank you very much and look forward to coming Friday.

By the way, the link is broken, I am getting a 404 error.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment