Skip to content

Instantly share code, notes, and snippets.

@noweh
Created October 7, 2022 20:18
Show Gist options
  • Save noweh/cea07cbab5892934b8f15ec81a6e800b to your computer and use it in GitHub Desktop.
Save noweh/cea07cbab5892934b8f15ec81a6e800b to your computer and use it in GitHub Desktop.
PHP Move given value to the end of the list
<?php
$array = [12, 0, 8, 1, 0, 39, 0, 7];
$searchedValue = 0;
$j=0;
for ($i=0; $i< count($array); ++$i) {
if ($array[$i] !== $searchedValue) {
if ($i !== $j && $array[$j] === $searchedValue) {
$array[$j] = $array[$i];
$array[$i] = $searchedValue;
}
++$j;
}
}
print_r($array);
// Array ( [0] => 12 [1] => 8 [2] => 1 [3] => 39 [4] => 7 [5] => 0 [6] => 0 [7] => 0 )
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment