I’ve just started to learn PHP, and I require some assistance. I’ve written a script that sorts an array of values from biggest to smallest. So, the biggest value will be stored in index position [0] and the smallest will be stored in index position [2]. The script works as expected, but I want to know why my first attempt didn’t work properly. The source code for my first and second attempts look similar, but the first attempt produced an array sorted from smallest to biggest.

Thank you, any help will be appreciated.

First attempt – sorts array from smallest to biggest

<?php

$numbers = array(6, 28, 24);

$size = sizeof($numbers); //sizeof($numbers); returns the size of the array

for ($i = 0; $i < $size; $i++)

{

for ($j = 0; $j < $size; $j++)

{

```
if ($numbers[$i] < $numbers[$j])
{
$smallest = $numbers[$i];
$numbers[$i] = $numbers[$j];
$numbers[$j] = $smallest;
}
```

}

}

for ($x = 0; $x < $size; $x++)

print "$numbers[$x], ";

?>

Second attempt: WORKS – sorts array from biggest to smallest

<?php

$numbers = array(6, 28, 24);

$size = sizeof($numbers); //sizeof($numbers); returns the size of the array

for ($i = 0; $i < $size; $i++)

{

for ($j = 0; $j < $size; $j++)

{

```
if ($numbers[$j] < $numbers[$i])
{
$smallest = $numbers[$j];
$numbers[$j] = $numbers[$i];
$numbers[$i] = $smallest;
}
```

}

}

for ($x = 0; $x < $size; $x++)

print "$numbers[$x], ";

?>