I want to have agentid generated randomly and unique to every agent. so i wrote this code but i get error message undefined variable $agentid. please, who can help me identify the problem, why my code is not generating agentid
$n=7;
function getRandomString($n) {
$characters = '0123456789,abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $n; $i ) {
$index = rand(0, strlen($characters) - 1);
$randomString .=$characters[$index];
}
return $randomString;
$agentid = getRandomString($n);
}
CodePudding user response:
Php has a function for generate unique id.
Uniqid();
https://www.php.net/manual/es/function.uniqid.php
But if you want to continue with your function the problem is that you declare $agentid inside the it and after the return, that cause the end of the process.
In resume you have to put the $agentid line out of the function not inside.
CodePudding user response:
There is an error in your usage. You should use it as follows.
<?php
function getRandomString($n) {
$characters = '0123456789,abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $n; $i ) {
$index = rand(0, strlen($characters) - 1);
$randomString .=$characters[$index];
}
return $randomString;
}
$n=7;
$agentid = getRandomString($n);
echo $agentid;
?>