user3358884
user3358884

Reputation: 109

php From largest to smallest and vise versa not working accordingly

I am new to php and I am doing this assignment that I am only supposed to do the missing code of the whole code using for loop. Can any one please help me what I am missing? Thank you in advance! Hoping my for loop works fine, the output I am getting is:

Order in the beginning: 4,7,-2,0,6
Largest to smallest: Array
Smallest to largest: Array

Instead was supposed to be for example:

Order in the beginning: 4,7,-2,0,6
Largest to smallest: 7,6,4,0,-2
Smallest to largest: -2,0,4,6,7

Assignment:

Complete the following PHP script so that it prints the numbers, given in a form, in a specific order. The script should organize the numbers from largest to the smallest and from smallest to largest and print both of these number strings on screen. The points are sent to the script as a character string, where points are separated with comma (e.g. 4,5,2). Points are divided into an array with the explode-function. Using the sort-function is not allowed. Do the organizing with a for-statement. Incomplete program:

<?php

    $numberstring = $_GET['numberstring'];

    $array = explode(',',$numberstring);



    echo "Order in the beginning: $numberstring\n";



    // Your code here and only here



    echo "Largest to smallest: $largest_smallest\n";

    echo "Smallest to largest: $smallest_largest\n";

?>

My code which arranges the input in descending and descending order:

for ($j = 0; $j < count($array); $j++) {
    for ($i = 0; $i < count($array) - 1; $i++) {
        if ($array[$i] > $array[$i + 1]) {
            $temp = $array[$i + 1];
            $array[$i + 1] = $array[$i];
            $array[$i] = $temp;

        }

    }
 $largest_smallest=$array;  
}


for ($j = 0; $j < count($array); $j++) {
    for ($i = 0; $i < count($array) - 1; $i++) {
        if ($array[$i] < $array[$i + 1]) {
            $temp = $array[$i + 1];
            $array[$i + 1] = $array[$i];
            $array[$i] = $temp;

        }
    }
    $smallest_largest=$array;
}

Upvotes: 0

Views: 477

Answers (1)

MueR
MueR

Reputation: 977

Basically, you see Array because you can't print an array like you would a string. If you want the output in the same form as the input, comma separated, you'll need to use a function to do so. If explode turns a string into an array by splitting it on a delimiter, could you think of a name for a function that does the opposite? The hint is in the name.

Upvotes: 1

Related Questions