How can you optimize the use of array_rand() to avoid inconsistent results in PHP code?

When using array_rand() in PHP to select random elements from an array, it's important to set the second parameter to specify the number of elements to pick. This ensures consistent results and avoids unexpected behavior. By providing the number of elements to select, you can optimize the use of array_rand() and prevent inconsistencies in your code.

// Avoid inconsistent results by specifying the number of elements to pick
$colors = ['red', 'blue', 'green', 'yellow', 'orange'];
$randomColors = array_rand($colors, 2);

foreach($randomColors as $index){
    echo $colors[$index] . "\n";
}