Skip to content
Advertisement

How to find value?

I make this associative array with PHP.

$colors = ['a' => 'red', 'b' => 'green', 'c' => 'blue', 'd' => 'yellow', 'e' => 'pink'];

Now by using array_rand() function =>

$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

$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

red
blue
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement