4

I have a project in which I need to generate a unique 5 digit alphanumeric ID for the user. How can I achieve this using codeigniter!?

thanks

Maverick
  • 2,738
  • 24
  • 91
  • 157
  • I haven't tried this yet but could you not just use vanilla PHP's dechex(int);? – scunliffe Dec 24 '10 at 16:25
  • You can check this post with quite similar requirement. http://stackoverflow.com/questions/3289086/generate-10-digits-alphanumeric-value-in-php-with-first-third-fourth-digit-must – Alpesh Dec 24 '10 at 18:01

6 Answers6

13

There is a function for that in string helper called random_string.

$this->load->helper('string');
echo random_string('alnum',5);

Details

navruzm
  • 503
  • 3
  • 7
  • @navruzm, you need to check **uniqueness** in the loop, and to regenerate, or its just a regular random string.. – Farside Mar 04 '16 at 11:06
3

You could try using uniqid()

Ash
  • 8,583
  • 10
  • 39
  • 52
1

Since you need a unique id, then you should use a unique data from the user record (index for example) or just generate a random one and directly check it's occurrence in the DB.

Here are the two approaches:

  1. random strings
  2. Unique IDs
ifaour
  • 38,035
  • 12
  • 72
  • 79
0

The below piece of code has to be written under calculation field in sharepoint list to generate combination alpha numeric item id dynamically in the incremental model.

=field1&"-"&LEFT("00000",5-(LEN(TEXT([field2],"0"))))&TEXT([field2],"0")

filed1=contains the prefix alpha value i.e (xyz,abc)

field2=contains the starting value of the field1 range i.e (1,10,20)

output: xyz-00001,abc-00010..

maxhb
  • 8,554
  • 9
  • 29
  • 53
0

I would highly recommend to use UUID for such purposes, as you project definitely will grow into something more serious.

For example, here's how we do in our project UID generation:

<?php 
// ...
public function getUid($uid = null)
{
    while (! $this->isValid($uid)) {
        $uid = sprintf('%04x%04x%02x', mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xff));
    }
    return $uid;
}

or find out another thread, with more complicated algorithms of generating UUID v4

Community
  • 1
  • 1
Farside
  • 9,923
  • 4
  • 47
  • 60
0

Convert the user's numeric id (which I am assuming you already have) to base-36 using base_convert($id, 10, 36);

Mike C
  • 1,808
  • 15
  • 17