How can we implement the bubble sort algorithm in PHP?

The bubble sort algorithm can be implemented using the following PHP code:

function bubbleSort($arr) {
    $n = count($arr);
    for ($i = 0; $i < $n-1; $i++) {
        for ($j = 0; $j < $n-$i-1; $j++) {
            if ($arr[$j] > $arr[$j+1]) {
                // 交换相邻元素
                $temp = $arr[$j];
                $arr[$j] = $arr[$j+1];
                $arr[$j+1] = $temp;
            }
        }
    }
    return $arr;
}

// 测试
$arr = [64, 34, 25, 12, 22, 11, 90];
$result = bubbleSort($arr);
print_r($result);

Running the code above will output [11, 12, 22, 25, 34, 64, 90], which is the sorted array. The basic idea of the bubble sort algorithm is to continuously compare neighboring elements and swap their positions, ensuring that each round of iteration moves the largest (or smallest) element to the end of the array, thus achieving sorting.

bannerAds