note 105151 added to function.rand

From: Date: Sat, 30 Jul 2011 19:50:09 +0000
Subject: note 105151 added to function.rand
Groups: php.notes 
Request: Send a blank email to php-notes+get-182019@lists.php.net to get a copy of this message
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; } ---- Server IP: 69.147.83.197 Probable Submitter: 98.148.133.246 ---- Manual Page -- http://www.php.net/manual/en/function.rand.php Edit -- https://master.php.net/note/edit/105151 Del: integrated -- https://master.php.net/note/delete/105151/integrated Del: useless -- https://master.php.net/note/delete/105151/useless Del: bad code -- https://master.php.net/note/delete/105151/bad+code Del: spam -- https://master.php.net/note/delete/105151/spam Del: non-english -- https://master.php.net/note/delete/105151/non-english Del: in docs -- https://master.php.net/note/delete/105151/in+docs Del: other reasons-- https://master.php.net/note/delete/105151 Reject -- https://master.php.net/note/reject/105151 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#182019) next »