Creating unique array keys

I wrote the function below in a recent project, I needed to create unique keys for a small multidimensional array and store it in a session.

  1. <?php
  2. function createUniqueId($length = 6, array $db)
  3. {
  4. $alph = array("a", "b","c","d","f","g","h","j","k","l","m","n","p","r","s","t","v","w","x","y","z");
  5. $nums = array(1,2,3,4,5,6,7,8,9);
  6. $id = "";
  7. srand((double)microtime()*1000000);
  8. $max = $length/2;
  9. for($i = 1; $i {
  10. $id .= $alph[rand(0,20)];
  11. $id .= $nums[rand(0,8)];
  12. }
  13. // check if the key already exists
  14. if (!array_key_exists($id, $db)) {
  15. return $id;
  16. }
  17. else {
  18. // if it does,lets recurse the function
  19. createUniqueId($length, $db);
  20. }
  21. }
  22. ?>

If you like my content, please consider buying me a coffee.

Buy Me A Coffee