Skip to content

Instantly share code, notes, and snippets.

@Rapkalin
Last active October 21, 2022 14:46
Show Gist options
  • Save Rapkalin/e5ffd96f631b4314db5ae1256446cccf to your computer and use it in GitHub Desktop.
Save Rapkalin/e5ffd96f631b4314db5ae1256446cccf to your computer and use it in GitHub Desktop.
PHP function to move a searched value to the end of an array
public static function moveValueToTheEnd(array $array, $searchedValue) : array
{
dump('initial array', $array);
$j = 0;
for ($i = 0; $i < (count($array)); $i++) {
if ($array[$i] === $searchedValue && isset($array[$i + 1])) {
$array[$i] = $array[$i + 1];
$array[$i + 1] = $searchedValue;
if (isset($array[$j + 1]) && $array[$j + 1] != $searchedValue) {
$array[$j] = $array[$j + 1];
$array[$j + 1] = $searchedValue;
}
}
if ($array[$j] != $searchedValue) {
$j++;
}
}
return $array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment