That depends if you need unique value or not guessable value.
Unique Identifier
If you need unique value for each user, you can use the UUID, for example Mysql has the UUID, Microsoft SQL has the Unique Idenfifier (which is basically the same), that is using the databases. Or just use the auto increment option / ID option. PHP has the method php.net uniqid Or you can try to create your own rfc 4122
Not easily guessable
Basically your question. You can use also the openssl random function or some other variations of pseudo-random number generator. There is no way to my knowledge you can guarantee the uniquenes of the values generated. You can however try to lower the posibility of such colision by setting the number of combinations reasonably high and hope for the best.
Third option
There is Unique non-repeating random numbers thread about how to generate them, but i do not believe that they are more viable for your use than your question with a do-while cycle checking the validity.