防止重复的随机代码生成?

I need to prevent generated code from producing duplicate. Is this correct way to do it or are there much more efficient ways?

function generate_code ()
{       
    $s = get_random_code();

    // check if code is already in db
    if (is_in_db($s))
        return generate_code();
    else
        return $s;
}

What if after generating a code, another duplicated is generated?

function generate_code () 
{        
    $s = get_random_code(); 

    // check if code is already in db 
    while (is_in_db($s)) { 
      $s = get_random_code(); 
    } 

    return $s; 
} 

No need to do recursion.

You could use a while loop, to avoid possible recursion depth limits:

function generate_code ()
{       
    $s = get_random_code();

    // check if code is already in db
    while (is_in_db($s))
        $s = get_random_code();

    return $s;
}

Yeah there are. Concatenate you primarykey, add some unique column, if you want. And hash it. I'm not totally sure, but the risk of getting the same hash from 2 different values is really low. Some says, you are more likely to win the lotto, be destroyed by an asteroid and struck by a lighting at the same time.

No need to check database,

<?php

    uniqid (rand(), true); 

?>