For the string profile.php?userId=55, explode('=', $string, 2) puts 55 at array index 1, not index 2. If the URL may contain additional parameters, parse the query string and retrieve the named userId instead.
Get the value with explode()
When the input has the exact form profile.php?userId=55, split once at the equals sign:
$string = 'profile.php?userId=55';
$parts = explode('=', $string, 2);
echo $parts[1]; // 55
PHP arrays use zero-based indexes, so $parts[0] contains profile.php?userId and $parts[1] contains 55. There is no third element. The positive limit of 2 means the result has at most two elements; it does not make explode() interpret URL parameters. See the PHP explode() manual.
Parse the query when there may be other parameters
If the URL can include other query parameters, extract the query and parse it by parameter name. This continues to work if parameters are reordered or added:
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Clear out junk files and repair common Windows errorsFree Scan →#1 Best Overall
$url = 'profile.php?userId=55&tab=posts';
$query = parse_url($url, PHP_URL_QUERY);
$params = [];
if ($query !== null && $query !== false) {
parse_str($query, $params);
}
$userId = $params['userId'] ?? null;
parse_url() extracts the query component; parse_str() turns its named parameters into an array. Passing $params as the second argument to parse_str() is required in PHP 8 and later. Consult the PHP parse_url() manual and PHP parse_str() manual.
Choose the approach that fits the input
| Approach | Best for | What it returns |
|---|---|---|
explode('=', $string, 2) |
A known, simple string with one value after the equals sign | At most two pieces; the value is at index 1. |
parse_url() and parse_str() |
A query string with named parameters, including possible additional or reordered parameters | An array keyed by parameter names, such as $params['userId']. |
Decide what your application should do when userId is absent; the example uses null as a fallback, but the appropriate behavior depends on the application.
Quick Recap
Rank #4
Rank #2
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




