How can multiple instances of the same category be sorted and displayed in PHP?

When dealing with multiple instances of the same category in PHP, you can sort and display them by using the usort() function along with a custom sorting function. This custom function should compare the category values and return the sorting order based on your criteria, such as alphabetical order or numerical order. Once the array of categories is sorted, you can then loop through them and display each category as needed.

// Sample array of categories
$categories = ['Apple', 'Banana', 'Orange', 'Apple', 'Banana'];

// Custom sorting function
function custom_sort($a, $b) {
    return strcmp($a, $b); // Sort alphabetically
}

// Sort the categories array
usort($categories, 'custom_sort');

// Display sorted categories
foreach ($categories as $category) {
    echo $category . "<br>";
}