How can the PHP function array_rand() be correctly utilized to prevent unexpected outcomes in conditional logic?

When using the PHP function array_rand() to randomly select an element from an array for conditional logic, it's important to store the result in a variable to prevent unexpected outcomes. If the result is directly used in conditional statements, the random selection may change with each comparison, leading to inconsistent behavior. By storing the random element in a variable before using it in conditionals, you ensure that the same element is used consistently throughout the logic.

$colors = ['red', 'blue', 'green', 'yellow'];
$randomColor = $colors[array_rand($colors)];

if ($randomColor == 'red') {
    echo "The random color is red.";
} elseif ($randomColor == 'blue') {
    echo "The random color is blue.";
} elseif ($randomColor == 'green') {
    echo "The random color is green.";
} elseif ($randomColor == 'yellow') {
    echo "The random color is yellow.";
}