MadnessRed Posted November 6, 2008 Share Posted November 6, 2008 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 https://forums.phpfreaks.com/topic/131692-solved-select-rand-from-an-array-but-slightly-differnt/ Share on other sites More sharing options...
rhodesa Posted November 6, 2008 Share Posted November 6, 2008 $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 https://forums.phpfreaks.com/topic/131692-solved-select-rand-from-an-array-but-slightly-differnt/#findComment-684033 Share on other sites More sharing options...
DeanWhitehouse Posted November 6, 2008 Share Posted November 6, 2008 Erm,maybe? $aray = array( 1 => 'a', 2 => 'b', 3 => 'c', 4 => 'd', 6 => 'e'); $aray = shuffle($aray);? echo $aray(1); of do an if statement using rand(); Link to comment https://forums.phpfreaks.com/topic/131692-solved-select-rand-from-an-array-but-slightly-differnt/#findComment-684034 Share on other sites More sharing options...
MadnessRed Posted November 6, 2008 Author Share Posted November 6, 2008 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 https://forums.phpfreaks.com/topic/131692-solved-select-rand-from-an-array-but-slightly-differnt/#findComment-684051 Share on other sites More sharing options...
rhodesa Posted November 7, 2008 Share Posted November 7, 2008 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 https://forums.phpfreaks.com/topic/131692-solved-select-rand-from-an-array-but-slightly-differnt/#findComment-684249 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.