What are the best practices for ensuring consistent encoding of special characters in URLs when building dynamic URLs in PHP?

Special characters in URLs need to be properly encoded to ensure that the URL is valid and works correctly across different platforms and browsers. One way to ensure consistent encoding of special characters in URLs when building dynamic URLs in PHP is to use the `urlencode()` function to encode the parameters before appending them to the URL.

// Example of building a dynamic URL with encoded special characters
$param1 = "Hello World!";
$param2 = "This is a test";
$encoded_param1 = urlencode($param1);
$encoded_param2 = urlencode($param2);

$url = "http://example.com/api?param1=$encoded_param1&param2=$encoded_param2";

echo $url;