To sort items of a Set in PHP, you can convert the Set to an array and use the sort()
function.
In this example,
$numberSet
with a set of numeric values.$numberSet
to an array using the iterator_to_array()
function.sort()
function to sort the items in ascending order.print_r()
.<?php
$numberSet = new SplObjectStorage();
$numbers = [5, 3, 8, 1, 2];
foreach ($numbers as $num) {
$numberSet->attach((object) ['num' => $num]);
}
$array = iterator_to_array($numberSet);
usort($array, function($a, $b) { return $a->num <=> $b->num; });
print_r(array_map(function($obj) { return $obj->num; }, $array));
?>
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 5 [4] => 8 )
In this example,
$stringSet
with a set of string values.$stringSet
to an array using the iterator_to_array()
function.usort()
function to sort the items in alphabetical order.print_r()
.<?php
$stringSet = new SplObjectStorage();
$strings = ["banana", "apple", "cherry", "date"];
foreach ($strings as $str) {
$stringSet->attach((object) ['str' => $str]);
}
$array = iterator_to_array($stringSet);
usort($array, function($a, $b) { return strcmp($a->str, $b->str); });
print_r(array_map(function($obj) { return $obj->str; }, $array));
?>
Array ( [0] => apple [1] => banana [2] => cherry [3] => date )
In this tutorial, we learned How to Sort Items of a Set in PHP language with well detailed examples.