Bubble Sort in PHP and Python
<p>As far as I can tell, these two programs should do exactly the same thing. However, the Python version works and the PHP one doesn't. What am I missing please?</p>

<pre><code>def bubbleSort(alist):
    for passnum in range(len(alist)-1,0,-1):
        for i in range(passnum):
            if alist[i]&gt;alist[i+1]:
                temp = alist[i]
                alist[i] = alist[i+1]
                alist[i+1] = temp

my_list = [2,3,5,4,1]
bubbleSort(my_list)
print(my_list)
</code></pre>

<hr>

<pre><code>&lt;?php
// Bubble Sort
$my_list = [2,3,5,4,1];

function bubble_sort($arr){
    $size = count($arr);
    for($pass_num = $size - 1; $pass_num &gt;= 0; $pass_num--){
        for($i = 0; $i &lt; $pass_num; $i++){
            if($arr[i] &gt; $arr[$i + 1]){
                swap($arr, $arr[i], $arr[$i+1]);
            }
        }
    }
}


function swap(&amp;$arr, $a, $b) {
    $tmp = $arr[$a];
    $arr[$a] = $arr[$b];
    $arr[$b] = $tmp;
}

bubble_sort($my_list);
print_r ($my_list);
</code></pre>

<p>The sort is in fact working, but as you dont pass a reference to the <code>bubble_sort($arr)</code> function you never get to see the actual result. Telling <code>bubble_sort()</code> that the array is being passed by reference means you are changing <code>$my_list</code> and not a copy of <code>$my_list</code></p>

<p>Oh and you had some compile errors, using <code>$arr[i]</code> instead of <code>$arr[$i]</code></p>

<pre><code>// Bubble Sort
$my_list = [2,3,5,4,1];

function bubble_sort(&amp;$arr){    // &lt;-- changed to &amp;$arr
    $size = count($arr);
    for($pass_num = $size - 1; $pass_num &gt;= 0; $pass_num--){
        for($i = 0; $i &lt; $pass_num; $i++){
            if($arr[$i] &gt; $arr[$i + 1]){
                // also changed this line to pass just the indexes
                swap($arr, $i, $i+1);   
            }
        }
    }
}


function swap(&amp;$arr, $a, $b) {
    $tmp = $arr[$a];
    $arr[$a] = $arr[$b];
    $arr[$b] = $tmp;
}

bubble_sort($my_list);
print_r ($my_list);
</code></pre>

<p>If you are testing this on a live server where error reporting is turned off add these lines to the top of any script you are developing, while you are developing it.</p>

<pre><code>&lt;?php
error_reporting(E_ALL); 
ini_set('display_errors', 1);
</code></pre>

<p>And the compile errors would have shown on the web page</p>

php python bubble-sort