0

You have to make sorting in the form of 1-dimensional arrays that can be filled dynamically with while arbitrarily, then the output must be sorted from small to large nominal.

Example:

Enter numbers: 2

Enter a number: 7

Enter numbers: 3

Enter a number: 8

Enter a number: 15

Enter a number: 9

Enter a number: 20

Enter a number: 4

Sorting results: 2, 3, 4, 7, 8, 9, 15, 20

  • note: this is just an example, if you use the while input is not limited, use php ...

this my code, is it true?

echo "<form method=post action=index.php>";
$i=0;
while($i<5){ 
    echo "<input type = text name = txt$i> <br><br>";
    $i++;
}
echo "<input type = submit value = submit>";
echo "</form>";

$a = array();

if (isset($_POST['txt0'])) {
    $i=0;
    while($i<5){ 
        $a[$i] = $_POST['txt'.$i];
        $i++;
        sort($a);
    }

    echo "<pre>";
    print_r($a);
    echo "</pre>";
}
Agung kusuma
  • 49
  • 1
  • 5
  • If you just need to sort the array, you may consider using the php `sort()` function maybe? – Uzair Hayat Feb 23 '20 at 15:39
  • @UzairHayat the OP has `sort` in their given code. – Progrock Feb 23 '20 at 15:47
  • What's the problem here? I'd move the sort to after the while loop. – Progrock Feb 23 '20 at 15:49
  • @Progrock oh dear, not sure how I missed that. – Uzair Hayat Feb 23 '20 at 16:27
  • i mean, what's the meaning "make sorting in the form of 1-dimensional arrays that can be dynamically filled in arbitrarily" ? is that relate to my code? – Agung kusuma Feb 23 '20 at 16:43
  • Don't `name` your input field with a counter -- use braces to indicate that `txt` values should be stored as an array in `txt[]` of the `$_POST` superglobal. – mickmackusa Feb 23 '20 at 21:14
  • I read 'arbitrary' as there's no restriction on the amount of inputs, or rather it could vary. A simple CLI script as this would satisfy your question: `while($num = readline('Enter number:')) $nums[] = $num; sort($nums); echo 'Results: ', implode(',', $nums);` . (Your example code satisfies the question when run through a web server for five inputs.) – Progrock Feb 23 '20 at 22:31

1 Answers1

0

The question, as it is phrased above, is unclear in many points. Therefore this answer can only be guess work. What I can confirm is that your script will basically work in the way that it will sort the values a user entered in the input fields and present them in a <pre> element.

However, you make it unnecessarily complicated. The second part of your script can be simplified to

if (isset($_POST['txt0'])) {
  sort($_POST);
  echo "<pre>";
  print_r($_POST);
  echo "</pre>";
}

This will deliver exactly the same result. An associative array (like The $_POST array) will be converted into a numeric one after sort() has been applied to it.

Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43