Newbie requiring answer to question

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] &lt; $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] &lt; $numbers[$i])
{
  $smallest = $numbers[$j];
  $numbers[$j] = $numbers[$i];
  $numbers[$i] = $smallest;
}

}

}

for ($x = 0; $x < $size; $x++)
print "$numbers[$x], ";

?>

if ($numbers[$i] < $numbers[$j])
vs
if ($numbers[$j] < $numbers[$i])

Lets pretend $numbers[i] is 6, and $numbers[j] is 28

if (6 is less than 28) // statement is true
vs
if (28 is less than 6) // statement is false

You’re comparing in a different direction. Now, I see you also changed the code inside that if statement, but think about it for a second. There’s only two array elements involved here, and it really doesn’t matter which one you call smallest at this point. If you swap the values of two array elements, the end result is the same. Even though it may take you 3 steps(3 lines of code) to do, you should think of swapping as a single operation.

If it’s still not very clear to you why the order gets reversed, let me know. Maybe I can help you visualize it.