How to order numbers from an array?

Asked

Viewed 1,050 times

5

I do not find the function to sort, increasingly, the numbers drawn.

<?php
   $resultado = array();
   for ($i = 0; $i <= 5; $i++){
        array_push($resultado,rand(1,60));
   }

   print_r($resultado); # Exibe os números sorteados fora de ordem.
   # print_r(sort($resultado)) # Exibe apenas o número 1
  • Perfect!!! Something so simple and I didn’t use the correct order. Thank you very much.

  • Take a look at [tour]. You can accept an answer if it solved your problem. You can vote on every post on the site as well. Did any help you more? You need something to be improved?

  • Just complementing... Beyond the sort, there are many other options, each one specific to a case. Documentation: Ordaining

2 answers

6

You know how to do, just don’t know how to see the result. The function sort() realize what you want upon your own array that you pass. Then you just print the array again after going through the function everything will work out. You just can’t have the function return printed because according to the documentation (has to read it to learn, alias has to read everything to program, to use new sites, etc., read is the secret to evolve), it returns a booliano whether it worked or failed. She returns no other array ordained.

<?php
$resultado = array();
for ($i = 0; $i <= 5; $i++) array_push($resultado, rand(1, 60));
print_r($resultado);
sort($resultado);
print_r($resultado);

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Excellent observation! Thank you.

5

To function sort($resultado) does not return the ordered array but rather a boolean if run without errors, or with errors..

The correct way to use is:

sort($resultado);

and then, print_r($resultado).

That is to say:

$resultado = array();
for ($i = 0; $i <= 5; $i++){
    array_push($resultado, rand(1,60));
}

sort($resultado);
print_r($resultado);

example: https://ideone.com/lcYGO9

  • 2

    Perfect!! Thanks for the excellent guidance.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.