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.

$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);

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];

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.