In what scenarios would it be advisable to use http_build_query instead of manually constructing URLs with variables in PHP, especially considering security concerns?

When constructing URLs with variables in PHP, it is advisable to use http_build_query instead of manually concatenating the variables to avoid syntax errors and ensure proper encoding of special characters. This function also helps prevent security vulnerabilities such as injection attacks by automatically encoding the variables.

// Using http_build_query to construct a URL with variables
$base_url = 'http://example.com/api';
$parameters = array(
    'name' => 'John Doe',
    'age' => 30,
    'email' => 'john.doe@example.com'
);

$url = $base_url . '?' . http_build_query($parameters);

echo $url;