How can PHP handle sorting and appending variables in a URL string efficiently?

When sorting and appending variables in a URL string in PHP, it is efficient to use the `http_build_query()` function to handle the sorting of variables and appending them to the URL. This function takes an associative array of variables and constructs a URL-encoded query string. By using this function, you can easily add or modify variables in the URL without manually concatenating strings.

// Sample code to sort and append variables in a URL string efficiently
$base_url = 'https://example.com/page.php';
$variables = array(
    'param1' => 'value1',
    'param2' => 'value2',
    'param3' => 'value3'
);

$query_string = http_build_query($variables);
$url = $base_url . '?' . $query_string;

echo $url;