0

I trying to sort an array ising php but this code is not working. can any body tell me whats wrong with this code, is my logic is right or wrong. I don't know much about Php as I am new to learning php

<? php

$a= array(12,5,78,10,63,11);
$size=$sizeof($a);

for($i=0;$i<=$size;$i++)
{
          for($j=$i+1;$j<$a[$i];$j++)
          {
                 if($a[$i]>$j)
              {

                   $temp=$a[i];
                   $a[$i]=$j;
                   $j=$temp;

               }

           }
}

for($i=0;$i<=$size;$i++)
{
echo $a[$i];
echo"<br/>"


}


?>
4
Contributors
3
Replies
4
Views
5 Years
Discussion Span
Last Post by Que336
1

If you're new to PHP, read the docs at PHP.net.

For this specific problem, try the sort function.

$a = array(12,5,78,10,63,11);
sort($a, SORT_NUMERIC);

// $a = array(5,10,11,12,63,78);
0

Your code is wrong. It has a couple of syntax errors and you're accessing your array out of bounds. The last valid index for an array of size n is n-1, so your for-loops should use <, not <=. Also the inner for-loop doesn't ensure that $j is a valid index at all.

Your logic is also wrong.

Your inner for-loop doesn't make any sense at all to me. Why do you use the value of $j directectly? Shouldn't it be an index into the array?

Also what sorting algorithm is this supposed to be? It sort of looks like a weird mix between selection sort and bubble sort. It's not going to work like this.

PS: PHP already has a built-in sorting function, so there's no need to build one yourself except for learning purposes.

0

Hey there buddy, I'll try and help you.

<?php
 $a= array(12,5,78,10,63,11);
 $size=count($a);//counts elements in the array
 sort($a);//sorts elements in the array, no need for those loops    
?>

To find out more about sorting arrays take a look at http://php.net/manual/en/array.sorting.php

I hope this helps

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.