I have an array like so
Array
(
[5] => 0
[6] => 0
)
the key 5 and key 6 are user id's. the value 0 for both the keys are the number of posts they have.
How do i obtain the user with the lowest post and if there are more than 1 user with the same/lowest post, select one by random.
Thank you
What you need is min()
for the lowest value in the array and array_rand()
to get a random entry out of the array.
$yourArr = array(4, 4, 3, 5);
$lowestEntry = min($yourArr);
$duplicateEntries = array_keys($yourArr, $lowestEntry);
echo (count($duplicateEntries) > 1)?$yourArr[array_rand($duplicateEntries, 1)]:$lowestEntry;
Let's say your array is $arr
$mini = min($arr);
$user = array();
foreach ($arr as $key => $val){
if ($val == $mini){
// find the user with minimum value
$user[] = $key;
}
}
// print the user with minimum value
echo array_rand($user, 1).' '.$mini;