Why is it important to use urlencode() or http_build_query() when passing values in URLs in PHP?

When passing values in URLs in PHP, it is important to use urlencode() or http_build_query() to properly encode special characters and prevent issues such as broken URLs or injection attacks. urlencode() is used to encode individual values, while http_build_query() is used to encode an array of values into a query string.

// Using urlencode() to encode individual values
$value = "Hello World!";
$encoded_value = urlencode($value);
echo "Encoded value: " . $encoded_value;

// Using http_build_query() to encode an array of values
$params = array(
    'name' => 'John Doe',
    'age' => 30
);
$query_string = http_build_query($params);
echo "Query string: " . $query_string;