I make this associative array with PHP.
JavaScript
x
$colors = ['a' => 'red', 'b' => 'green', 'c' => 'blue', 'd' => 'yellow', 'e' => 'pink'];
Now by using array_rand() function =>
JavaScript
$newArray = array_rand($colors, 2);
The Output is: [0] => a [1] => b
This output shows me only the key of the array. But I want to see the value too. How can I find the value of this array using array_rand()?
Advertisement
Answer
Use the keys to access the original array
JavaScript
$colors = ['a' => 'red', 'b' => 'green', 'c' => 'blue', 'd' => 'yellow', 'e' => 'pink'];
$rand_keys = array_rand($colors, 2);
foreach ($rand_keys as $key) {
echo $colors[$key] . PHP_EOL;
}
RESULT
JavaScript
red
blue