How do I explode this string and get the user id

Hello,

I have this string:

$String = "profile.php?userId=55";

I want to get the number 55, this code just not do it:


$getID = explode("=",$String,2);

echo $getID[2],"<br/>";

Please help
Thanks

http://php.net/manual/en/reserved.variables.get.php

Oops, I didn’t read your question too well. My answer makes no sense, sorry.

It’s in $getID[1];, not $getID[2];. In PHP array’s are 0-based, i.e., the first part is in $getID[0]; and the second part is in $getID[1];.

In cases like this it’s always a good idea to do a var_dump($getID); to see what’s going on.

Also… i wouldnt do it this way unless you -know- that the URL will only ever contain one variable.

For example; if someone sent this as your string:

“profile.php?userId=55&moo=cow”

Then your script will tell you that the value of userId is “55&moo=cow”

For this purpose I’d suggest using some more elegant solutions:

  1. parse_url() to get the query part.
  2. parse_str() to get the userId. This way your code is future-proof in case you add more parameters in the future.

Thank you Lemon,

That’s exactly what I’m looking for. Very appreciated.