Jump to content

php sorting numbers with for-statement


danielki

Recommended Posts

Hello, I am new to php and am trying to do the following task.

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";

?>

First I tried it if it works with the following straight forward code:

$largest_smallest=rsort($numberstring );
$smallest_largest=sort($numberstring );

And it gave me the following error:

Order in the beginning: 4,7,-2,0,6

Warning: rsort() expects parameter 1 to be array, string given in /tmp/K2U5XgShJ9/1/.php on line 9
 
Warning: sort() expects parameter 1 to be array, string given in /tmp/K2U5XgShJ9/1/.php on line 10
Largest to smallest: 
Smallest to largest: 

So can any one help me why there is an error and also according to the assignment I am supposed to do it with for statement. what is the equivalent way of sort() or rsort() doing this? thank you so much!

 

Example output:

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
Edited by danielki
Link to comment
Share on other sites

you are seperating it based on ',' and storing it in $array, but for sort you are giving the string again. Hence the error.

you should call sort($array) and not sort($numberstring)

 

also you do not need to assign it to a variable,it sorts and stores it in the array given.

sample below.

<?php
$num = "1,4,2,5,2,8";
$array = explode(',',$num);
sort($array);
var_dump($array);
?>
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.