Jump to content

[SOLVED] Select rand from an array, but slightly differnt.


MadnessRed

Recommended Posts

What i want is to do is pick a random value from an array.

 

eg

 

$aray = array(

1 => 'a',

2 => 'b',

3 => 'c',

4 => 'd',

6 => 'e');

 

I want it to pick a number out of 1,2,3,4,6 (but not 5) and then to return that number and nothing else.

 

Any idea how I would got about doing that.

Link to comment
Share on other sites

$array = array(
1 => 'a',
2 => 'b',
3 => 'c',
4 => 'd',
6 => 'e');
$keys = array_keys($array);
shuffle($keys);
print $keys[0];

 

edit: just realized, this is better:

$array = array(
1 => 'a',
2 => 'b',
3 => 'c',
4 => 'd',
6 => 'e');
print array_rand($array);

Link to comment
Share on other sites

the thing is I dont want the a,b,c bit, i want the 1,2,3 bit.

 

Also the array is in a specific order, so I can't shuffle.

 

But I think I got any idea.

 

$array = array(

1 => array(1,'a'),

2 => array(2,'b'),

3 => array(3,'c)',

4 => array(4,'d)',

6 => array(6,'e'));

 

$temp = array_rand($array)

$id=$temp[0];

Link to comment
Share on other sites

What you are looking for is picking a random KEY from the array. The purpose of array_rand() is to return a random KEY from an array. So this:

$array = array(
1 => 'a',
2 => 'b',
3 => 'c',
4 => 'd',
6 => 'e');
print array_rand($array);

will return 1, 2, 3, 4, or 6 randomly.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.