Skip to content
PHP Logo

What solution was suggested to address the alphabetical sorting of the random selection?

The issue of alphabetical sorting of a random selection can be addressed by sorting the array before selecting a random element. This ensures that the random selection will be from a sorted list of elements.

php
// Sample array of elements
$elements = ['Apple', 'Banana', 'Orange', 'Mango', 'Grape'];

// Sort the array alphabetically
sort($elements);

// Select a random element from the sorted array
$randomElement = $elements[array_rand($elements)];

echo $randomElement;