Example 1 — Pick a Random Key
The exact key changes every run, so this example checks what kind of thing comes back.
<?php
$fruits = ["a" => "apple", "b" => "banana", "c" => "cherry"];
$key = array_rand($fruits);
echo gettype($key), PHP_EOL;
echo array_key_exists($key, $fruits) ? "valid key" : "missing key", PHP_EOL;
echo is_string($fruits[$key]) ? "value is a string" : "other", PHP_EOL; How It Works
- Create an array. The keys are the strings
a,bandc. - Call array_rand(). It returns one of those keys, but we do not know which.
- Check what came back. It is a string because the keys are strings.
- Read the value. Using the key with
$fruits[$key]always works.

