0

I have a task of sorting an array of numbers in both ascending and descending order. The challenge is, I can't use the built-in sort function, but loop through the array with for-loops instead.

I am a total newbie when it comes to PHP and this task straight off baffles me. Here is the code I'm supposed to work with:

<?php
  $arr = $_GET['arr'];
  $table = explode(',', $arr);
  
  $count = count($table);
  
  // What I tried to work with, didn't get to work:
  for ($i = 0; $i < $count; $i++) {
      for ($j = $i + 1; $j < $count; $j++) {
          if ($table[$i] > $table[$j]) {
              $temp = $table[$i];
              $table[$i] = $table[$j];
              $table[$j] = $temp;
              $asc = implode("," $temp);
          }
      }
  }
  
  echo "Ascending: $asc";
  echo "Descending: $desc";
?>

Any clue why this doesn't run? At some point, I got the first (largest) number in the array with the echo, but don't really know what broke that either.

2 Answers 2

1

Move the line

$asc = implode(",", $table);

from its current location below the outer for loop and maybe add the line

$desc = implode(",", array_reverse($table));

to get the descending sort order.

Sign up to request clarification or add additional context in comments.

1 Comment

This seemed to be the issue - big thanks for mentioning the array_reverse method as well, didn't even cross my mind! I would've just done the same for loop twice with different operator to accomplish this.
1

Many ways to make it. One solution you will find in the code below. you will certainly notice that the sorting depends only on one operator. Therefore, you can build a function out of it by specifying the sorting as a parameter. function(array $array, string $sort) {}

DESC

    $arr= array(112,21,130,140,2,42);
    for($i=0; $i<count($arr)-1; $i++)
    {
        for($j=0; $j<count($arr)-1; $j++)
        {
            if($arr[$j] < $arr[$j+1]){
                $temp= $arr[$j+1];
                $arr[$j+1]= $arr[$j];
                $arr[$j]= $temp;
            }
        }

    }
    print_r($arr);

Output:

Array
(
    [0] => 140
    [1] => 130
    [2] => 112
    [3] => 42
    [4] => 21
    [5] => 2
)

ASC

    $arr= array(112,21,130,140,2,42);
    for($i=0; $i<count($arr)-1; $i++)
    {
        for($j=0; $j<count($arr)-1; $j++)
        {
            if($arr[$j] > $arr[$j+1]){
                $temp= $arr[$j+1];
                $arr[$j+1]= $arr[$j];
                $arr[$j]= $temp;
            }
        }

    }
    print_r($arr);

Output

Array
(
    [0] => 2
    [1] => 21
    [2] => 42
    [3] => 112
    [4] => 130
    [5] => 140
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.