Page 1 of 1

rsort_strange_output

Posted: Tue Feb 21, 2012 12:04 pm
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?

Re: rsort_strange_output

Posted: Tue Feb 21, 2012 6:25 pm
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.

Re: rsort_strange_output

Posted: Fri Feb 24, 2012 11:29 am
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
)