rsort_strange_output

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
nellaikrishna
Forum Newbie
Posts: 2
Joined: Tue Feb 21, 2012 11:53 am

rsort_strange_output

Post by nellaikrishna »

Hello,

I tried to use rsort() to get values from a text file onto an array, sort in descending order and print it. The text file i used and php code are as follows:

strange.txt
50
69
8
15
99


strange.php

Code: Select all

<?php
echo "<pre>";
$handle = fopen('./in_strange.txt',r);
$a = array();
for($i = 0; $i<5; $i++)
{
	$a[] = fgets($handle);
}
print_r($a);
rsort($a);
print_r($a);
?>
output

Array
(
[0] => 50

[1] => 69

[2] => 8

[3] => 15

[4] => 99
)
Array
(
[0] => 99
[1] => 8

[2] => 69

[3] => 50

[4] => 15

)

Please help me out. Am i doing it right or is there any modifications needed?
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: rsort_strange_output

Post by Celauran »

It's treating them as strings, not integers, so it is sorting them correctly. Cast them as int to get the behaviour you were expecting.
nellaikrishna
Forum Newbie
Posts: 2
Joined: Tue Feb 21, 2012 11:53 am

Re: rsort_strange_output

Post by nellaikrishna »

Celauran wrote:It's treating them as strings, not integers, so it is sorting them correctly. Cast them as int to get the behaviour you were expecting.
Thanks Celauran.
Issue resolved.

Code: Select all

<?php
echo "<pre>";
$handle = fopen('./in_strange.txt',r);
$a = array();
for($i = 0; $i<5; $i++)
{
	$a[] = fgets($handle);
}
print_r($a);
echo gettype($a);
$b = array();

for($i=0; $i<count($a);$i++)
{
	$b[] = (int) $a[$i];
}
rsort($b);
print_r($b);
?>
The output is as desired.

Code: Select all

Array
(
    [0] => 50

    [1] => 69

    [2] => 8

    [3] => 15

    [4] => 99
)
Array
(
    [0] => 99
    [1] => 69
    [2] => 50
    [3] => 15
    [4] => 8
)
Post Reply