Skip to content

Instantly share code, notes, and snippets.

@robozavri
Created March 28, 2018 22:09
Show Gist options
  • Save robozavri/f4d37a9d9a270d50a3cd8ac79146c2d2 to your computer and use it in GitHub Desktop.
Save robozavri/f4d37a9d9a270d50a3cd8ac79146c2d2 to your computer and use it in GitHub Desktop.
sort array one by one
<?php
// Sets up our arrays
$array1 = [1, 3, 5, 7, 9];
$array2 = [2, 4, 6, 8, 10];
$array3 = [];
// Determines how many items we have in each array
$array1_count = count($array1);
$array2_count = count($array2);
// While we still have at least one item in one of the arrays
while ($array1_count || $array2_count)
{
$array1_empty = $array1 == [];
$array2_empty = $array2 == [];
if (!$array1_empty && !$array2_empty)
{
if (current($array1) < current($array2))
{
$array3[] = array_shift($array1);
$array1_count--;
}
else
{
$array3[] = array_shift($array2);
$array2_count--;
}
}
elseif (!$array1_empty)
{
$array3[] = array_shift($array1);
$array1_count--;
}
elseif (!$array2_empty)
{
$array3[] = array_shift($array2);
$array2_count--;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment