1

Hello I would like to have a code that displays randomly from an array a number and displays it. For example this code

<?php
$firstquarter = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>

will return

Array
(
    [1] => January
    [2] => February
    [3] => March
)

Instead of this, I would like to display on

6
  • Are you searching for something like array_rand? Your questions isn't that clear... Commented Jan 19, 2011 at 0:44
  • 1
    Again you're questing isn't very clear. Please clarify. Commented Jan 19, 2011 at 0:52
  • Noy your question is very unclear, what's defines the difference from 15:00 and 18:00 ? Commented Jan 19, 2011 at 0:52
  • 1
    Actually, I'm not changing my answer now, you should be creating a new post for this, its bad practise to totally change the whole question. Commented Jan 19, 2011 at 0:53
  • 1
    Rolled the revision back - you shouldn't change the question completely (as @RobertPitt mentioned). Start a new one. Commented Jan 19, 2011 at 0:56

3 Answers 3

3

A simple function called array_rand

example:

$selection = array_rand($my_array);

Documentation

Sign up to request clarification or add additional context in comments.

Comments

2

Use rand()

$iIndex = rand(1, count($firstquarter));
echo $firstquarter[$iIndex];

This assumes you have an one indexed array with consecutive keys.

3 Comments

Oh great for this. I found this code <?php echo rand(5, 15); ?> However I want a different range depends on time. For example if the server time is 15:00 to 18:00 it will have a different range than 18:01 to 21:00 and so on. UPDATED ENTIRE QUESTION
@RobertPitt Ha. never come across that function. Submit your own answer and I'll give you an up vote.
Hehe, by "so on" I mean you know 21:01 to 24:01... I need an example to know how it is working
2

You need array_rand():

echo $firstquarter[array_rand($firstquarter)];

I'm not sure if this is what you want but here it goes:

echo mt_rand(intval(date('H') / 3) * 4, intval(date('H') / 3) * 5);

2 Comments

The question has been rolled back as the OP changed the whole context of the question, +1 for posting anyway.
@RobertPitt: Yup, I see. I got somewhat confused with the rollback there.

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.