Last active
October 21, 2022 14:46
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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