0

So I've got this:

$h = $user_goals;

while($h > 0) {
randomScorer();
$minute = rand(0,90);
echo "(".$minute.")<br>";

$h--;

Basically, what it does is, $user_goals, has a load of factors drawn into it and creates a number, between 0-5, and this information is used to generate the times of the goals, using the above PHP function.

It's working, it's brilliant, etc. However, the numbers are appearing in random order in which they are generated and so I was wondering:

  • Is there any way to sort these numbers?

    Would I put them into an array during this iteration methodology, and then sort the array by the number's value?

Any help is greatly appreciated!

Prix
  • 19,417
  • 15
  • 73
  • 132
Bate Wes
  • 39
  • 4

2 Answers2

0

That is why PHP provides us Sort functions. Have a look here.

<?php

$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);

?>

Since your array is NUMERIC, you need to use the FLAG along with the sort function.

sort($goals, SORT_NUMERIC); 
print_r($goals);
Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
0

Same idea, using sort() but also uses range and array_walkto set up your array a little closer to how you already do it:

$goal_array = range(1, $user_goals); // Warning, assumes $user_goals is number

array_walk($goal_array, function(&$goal) {
   randomScorer();
   $goal = rand(0,90);
});

sort($goal_array, SORT_NUMERIC);
Anthony
  • 36,459
  • 25
  • 97
  • 163