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));
@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