2

Say we have an array like this with 1 being two values and 2 being two values and 3, etc

$language = array 
(
    "1"=>array
    (
      "Hola",
      "Spanish"
    ),
    "2"=>array
    (
      "Fáilte",
      "Irish"
    ),
    "3"=>array
    (
      "Yasou",
      "Greek"
    )
);

How would I randomly select ONLY 1 of 3 arrays and display the two values it has.

So something like this, $language[2][1], thats in $language[2][2].
Which should be, Fáilte, thats in Greek

2 Answers 2

4

PHP has it's own random array function: array_rand(). Use it like so:

$random_key = array_rand($language);
echo $language[$random_key][0];
echo $language[$random_key][1];
Sign up to request clarification or add additional context in comments.

Comments

1

You can choose a random set of words using the following code and then echo the two results like so:

$row = rand(0,sizeof($language)-1);
echo $language[$row][0];
echo $language[$row][1];

This is assuming that your array actually starts from 0 as most arrays do. If it really starts from 1, you can use the code posted in the answer below instead.

2 Comments

This code is wrong. It would choose a random first entry and a random second entry, not the first and second entry from the same array.
Furthermore, it will never select the last entry, and crash if it tries to select the zeroth.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.