-3

I'm receiving an integer value from my array, instead of a name. How can i correct my code to randomly select a name from the array?

$family = array();
        array_push($family, "joe");
        array_push($family, "bill");
        array_push($family, "carl");
    $sorted = sort($family);
    $select = rand(0, count($sorted) - 1);

    echo $select;
DevEarl
  • 18
  • 1
  • 3

2 Answers2

1
  1. sort() doesn't return the sorted array, it sorts the passed array by reference.
  2. Using rand() as you do will return a random index to use in the array like: echo $family[$select];.

If you don't need the array sorted for later an easier approach would be:

shuffle($family);
echo $family[0];

Or if you do need it sorted:

sort($family);
echo $family[array_rand($family)];
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
  • i think your mixing the sorting and the random picking up. with or without sorting i would not use shuffle (then pick 0), over array_rand. i would think the latter was more efficient. –  Dec 27 '15 at 22:23
0

Your code

$sorted = sort($family);
 $select = rand(0, count($sorted) - 1);
 echo $select;

Replaced by,

asort($family);
$select = array_rand($family);
echo "Randomly Selected array value==" . $family[$select];
Ramalingam Perumal
  • 1,367
  • 2
  • 17
  • 46