When should PHP developers manually apply urlencode to variables when constructing URLs, and when is it unnecessary?

When constructing URLs in PHP, developers should manually apply urlencode to variables that may contain special characters such as spaces, commas, or other reserved characters. This ensures that the URL is properly encoded and avoids any issues with invalid characters. If the variable is already properly encoded or does not contain any special characters, applying urlencode may be unnecessary.

// Manually applying urlencode to a variable before constructing a URL
$param = "Hello, World!";
$encoded_param = urlencode($param);
$url = "https://example.com/api?param=" . $encoded_param;
echo $url;