note 105151 deleted from function.rand by danbrown
| From: | danbrown@php.net | Date: | Mon, 01 Aug 2011 13:50:45 +0000 |
| Subject: | note 105151 deleted from function.rand by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-182058@lists.php.net to get a copy of this message | ||
Note Submitter: blee at misdivision dot com
----
This is the best function out there for getting a random string, numeric, symbols or a combination
of any. If includes some checking to ensure return types are selected, however, you can specify the
length and return types you want for your random value. Enjoy
function get_random_value($length = 10, $types = "ans") {
// Get the acceptable types
$data["types"] = str_split($types);
// Just a bit of checking to ensure the types requested are the types returned
if (count($data["types"]) > 3)
$data["types"] = "ans";
else if (empty($data["types"]))
$data["types"] = "ans";
else
foreach ($data["types"] as $type)
if (!in_array($type, array("a", "n", "s"))) {
$data["types"] = "ans";
break;
}
// Alpha values
if (in_array("a", $data["types"]))
$data["characters"] =
array("A","B","C","D","E","F","G","H","J","K","L","M",
"N","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");
// Numeric values
$data["numeric"] =
array("1","2","3","4","5","6","7","8","9");
if (in_array("n", $data["types"]))
if (!empty($data["characters"]))
$data["characters"] = array_merge($data["characters"],
$data["numeric"]);
else
$data["characters"] = $data["numeric"];
// Symbols values
$data["symbols"] =
array("&","*","(",")","#","@","=","!","-","=");
if (in_array("s", $data["types"]))
if (!empty($data["characters"]))
$data["characters"] = array_merge($data["characters"],
$data["symbols"]);
else
$data["characters"] = $data["symbols"];
// Declare key array to hold the values
$keys = array();
// While count of keys is less than the requested length, continue
for ($i = 0; $i < $length; $i++) {
$x = mt_rand(0, count($data["characters"])-1);
if (!in_array($x, $keys) or $i >= count($data["characters"]))
$keys[] = $x;
}
foreach($keys as $key)
$random_string .= $data["characters"][$key];
return $random_string;
}