How about just using shuffle
and grabbing the first item off of the array like this:
shuffle($myArray)
echo $myArray[0];
But honestly, your code is confusing. So what is the output of the $json
array—that isn’t JSON—if you do this?
echo '<pre>';
print_r($json);
echo '</pre>';
EDIT: With the updated question from the original poster, it seems like the array is nested in another array based on the structure:
Array (
[0] => Array (
[ID] => 13
[ANS1] => ducks
[ANS2] => chickens
[ANS3] => birds
[ANS4] => cats
[ANS5] => dogs
[ANS6] => elephants
[ANS7] => monkeys
[ANS8] => animals
[ANS9] => bees
)
)
Okay, so knowing that you would do this. I assuming that $json
is the array in this case:
$new_array = array_slice($json[0],1,9);
$random_key = array_rand($new_array);
$final_value = $new_array[$key];
So array_slice
is grabbing items 1-9 from $json[0]
and assigning it to $new_array
. Then we use array_rand()
to get a random key value from $new_array
. Now the final value is set as $final_value
with $new_array[$key]
.
I am using array_rand
here instead of the shuffle
I used before because it’s clear you want to preserve keys.