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


}


?>

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

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.

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.