tags:

views:

56

answers:

3

I would like to generate an alphanumeric employee id in PHP e.g. EP0001

Any ideas?

+2  A: 

We are going to need more than this to help you but this is what I would do.

Assuming EP is the start of every alphanumeric employee id then

<?php
$number = getTotalEmployees();

$id = 'EP'.$number;

function getTotalEmployees() {
    $num = 'Get number of Employees from database';
    ++$num; // add 1;

    $len = strlen($num);
    for($i=$len; $i< 4; ++$i) {
        $num = '0'.$num;
    }
    return $num;
}
?>

UPDATE

Thanks to Trefex If you use MySQL, you could store the employee ID in a field and set the ZEROFILL attribute. That way you don't have to deal with the zeroes in PHP

<?php
function getTotalEmployees() {
    $num = 'Get number of Employees from database';
    ++$num; // add 1;
    return $num;
}
?>
Lizard
If you use MySQL, you could store the employee ID in a field and set the ZEROFILL attribute. That way you don't have to deal with the zeroes in PHP.
Trefex
without some table locking going on, you have a race condition here.
Paul Dixon
also, a less verbose way to pad it would be return sprintf('%04d', $num);
Paul Dixon
thanks a lot for this.
fuz3d
A: 

You can go with the following code if you are looking for random id's

<?php 
  $numchars = rand(4,15); //You can specify the length here
  //This is the list from which id is generated.
  $chars =   explode(',','a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,0,1,2,3,4,5,6,7,8,9'); 
  $random=''; 
  //Do a random generation in a for loop
  for($i=0; $i<$numchars;$i++)  { 
    $random.=$chars[rand(0,count($chars)-1)]; 
  } 
  //Here you go.. Nice & pretty
  echo $random; 

?>

You can find this & more in Google itself

http://www.webmaster-talk.com/php-forum/29621-php-randomly-generate-alphanumeric-charachters.html

Shoaib
There is no need to word with arrays; you can access strings with the syntax `$str[12345]` too.
Gumbo
+1  A: 

Just do them sequentially, there's no need to 'code' data into a number such as "E means he's the Enterprise level employee and P means he parks in P-lot." This is an outdated way of doing things that's crept up from before databases existed. Encoding special meanings into a unique identifier that can change will be a nightmare, there's no need to do it and it's poor database design.

Alternately, if these numbers are prone to some level of fraud generate them in a non-sequential method, such as generating a psudo-random UID and checking if it is in use or not then assigning it.