In what scenarios should urlencode be used in PHP to ensure proper handling of special characters in URLs?

When passing data through URLs in PHP, special characters such as spaces, ampersands, and question marks can cause issues. To ensure proper handling of these special characters, urlencode should be used to encode the data before appending it to the URL. This function converts special characters into a format that can be safely transmitted in a URL, preventing any errors or unexpected behavior.

$data = "Hello World!";
$encoded_data = urlencode($data);
$url = "http://example.com?data=" . $encoded_data;

echo $url;