<? php
$order = array(
3452342,
5867867,
7867867,
1231233
);
$array = array(
array("id" => 7867867, "title" => "Must Be #3"),
array("id" => 3452342, "title" => "Must Be #1"),
array("id" => 1231233, "title" => "Must Be #4"),
array("id" => 5867867, "title" => "Must Be #2"),
array("id" => 1111111, "title" => "Dont Care #1"),
array("id" => 2222222, "title" => "Dont Care #2"),
array("id" => 3333333, "title" => "Dont Care #3"),
array("id" => 4444444, "title" => "Dont Care #4")
);
function custom_compare($a, $b){
global $order;
$a = array_search($a["id"], $order);
$b = array_search($b["id"], $order);
if($a === false && $b === false) { // both items are dont cares
return 0; // a == b
}
else if ($a === false) { // $a is a dont care item
return 1; // $a > $b
}
else if ($b === false) { // $b is a dont care item
return -1; // $a < $b
}
else {
return $a - $b;
}
}
shuffle($array); // for testing
var_dump($array); // before
usort($array, "custom_compare");
var_dump($array); // after
?>
- Output for 5.3.0 - 5.3.29, 5.4.0 - 5.4.32, 7.2.29 - 7.2.33, 7.3.16 - 7.3.31, 7.4.3 - 7.4.32, 8.0.0 - 8.0.12, 8.0.14 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.6
- <? php
$order = array(
3452342,
5867867,
7867867,
1231233
);
$array = array(
array("id" => 7867867, "title" => "Must Be #3"),
array("id" => 3452342, "title" => "Must Be #1"),
array("id" => 1231233, "title" => "Must Be #4"),
array("id" => 5867867, "title" => "Must Be #2"),
array("id" => 1111111, "title" => "Dont Care #1"),
array("id" => 2222222, "title" => "Dont Care #2"),
array("id" => 3333333, "title" => "Dont Care #3"),
array("id" => 4444444, "title" => "Dont Care #4")
);
function custom_compare($a, $b){
global $order;
$a = array_search($a["id"], $order);
$b = array_search($b["id"], $order);
if($a === false && $b === false) { // both items are dont cares
return 0; // a == b
}
else if ($a === false) { // $a is a dont care item
return 1; // $a > $b
}
else if ($b === false) { // $b is a dont care item
return -1; // $a < $b
}
else {
return $a - $b;
}
}
shuffle($array); // for testing
var_dump($array); // before
usort($array, "custom_compare");
var_dump($array); // after
?>
- Output for 8.0.13
- Parse error: syntax error, unexpected variable "$order" in /in/Is56P on line 3
Process exited with code 255. - Output for 7.3.32 - 7.3.33, 7.4.33
- Parse error: syntax error, unexpected '$order' (T_VARIABLE) in /in/Is56P on line 3
Process exited with code 255.
preferences:
167.35 ms | 401 KiB | 202 Q