Forum Moderators: coopster
private function UniqueKey(){
$setOne = range('A','Z');
$setTwo = range(0,9);
$UniqueKeyArray = array_merge($setOne,$setTwo);
shuffle($UniqueKeyArray);
$this->UniqueCode = "#".$UniqueKeyArray[rand(0,35)].$UniqueKeyArray[rand(0,35)].$UniqueKeyArray[rand(0,35)].$UniqueKeyArray[rand(0,35)]."#";
return $this->UniqueCode;
}
$code1 = $this->UniqueKey(); //#HJYE#
$code2 = $this->UniqueKey(); //#567E#
$sequence = $code1.$code1.$code3; //#HJYE##HJYE##567E#
echo $sequence;
//or however u need it to be, ie:
echo $code1;
echo $code1;
echo $code2; <?php
class Tester {
private $UniqueCode;
private $calls = 0; //counter to track which call to UniqueKey we are on
private $codes = array(); //storage to track codes output by UniqueKey
public function getKey() {
return $this->UniqueKey(4);
}
private function UniqueKey($repeatLimit = 2) { //optional parameter $repeatLimit (int) defaults to 2
$this->calls++;
if ($this->calls <= $repeatLimit && isset($this->UniqueCode)) {
return $this->UniqueCode;
}
$UniqueKeyArray = str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789');
//no need to shuffle, since we're already using rand()
$uniqueCode = "#".$UniqueKeyArray[rand(0,35)].$UniqueKeyArray[rand(0,35)].$UniqueKeyArray[rand(0,35)].$UniqueKeyArray[rand(0,35)]."#";
//ensure the code is truly unique and has not been previously output
//(at this point in the code we are either beyond the $repeatLimit or this is the very first call to UniqueKey)
while (in_array($uniqueCode, $this->codes)) {
$uniqueCode = "#".$UniqueKeyArray[rand(0,35)].$UniqueKeyArray[rand(0,35)].$UniqueKeyArray[rand(0,35)].$UniqueKeyArray[rand(0,35)]."#";
}
$this->UniqueCode = $uniqueCode;
array_push($this->codes, $uniqueCode); //track that we've used the code
return $this->UniqueCode;
}
}
$T = new Tester();
for ($i = 0; $i < 10; $i++) {
echo $T->getKey().'<br>';
}
?>
<?php
class Tester {
private $UniqueCode;
private $calls = 1; //counter to track which call to UniqueKey we are on
private $codes = array(); //storage to track codes output by UniqueKey
public function getKey() {
return $this->UniqueKey('2');
}
private function UniqueKey($repeatLimit=null) {
//Increment the number of calls to the function
$this->calls++;
//Catch here if the limit of repeats hasn't been reached & code is set/has state
if (($this->calls <= $repeatLimit) && isset($this->UniqueCode)) {
//return the same code until the $repeatLimit is reached
return $this->UniqueCode;
}
//reset the calls to 1 so that the counter starts at 1 because starting at 0 means the repeats is 1
$this->calls = 1;
//String to array, this is instead of using 2 seperate calls to range
$KeyArray = str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789');
//Arrange the 4 digit code
$uniqueCode = "#".$KeyArray[rand(0,35)].$KeyArray[rand(0,35)].$KeyArray[rand(0,35)].$KeyArray[rand(0,35)]."#";
return $this->UniqueCode = $uniqueCode;
}
}
$T = new Tester();
for ($i = 0; $i < 10; $i++) {
echo $T->getKey().'<br>';
}
?>