Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Well, you didn't clarify all the questions I asked in my comment, but I'll assume that you want a function that can take a string of "possible" characters and a length of string to return. Commented thoroughly as requested, using more variables than I would normally, for clarity:</p> <pre><code>function get_random_string($valid_chars, $length) { // start with an empty random string $random_string = ""; // count the number of chars in the valid chars string so we know how many choices we have $num_valid_chars = strlen($valid_chars); // repeat the steps until we've created a string of the right length for ($i = 0; $i &lt; $length; $i++) { // pick a random number from 1 up to the number of valid chars $random_pick = mt_rand(1, $num_valid_chars); // take the random character out of the string of valid chars // subtract 1 from $random_pick because strings are indexed starting at 0, and we started picking at 1 $random_char = $valid_chars[$random_pick-1]; // add the randomly-chosen char onto the end of our string so far $random_string .= $random_char; } // return our finished random string return $random_string; } </code></pre> <p>To call this function with your example data, you'd call it something like:</p> <pre><code>$original_string = 'abcdefghi'; $random_string = get_random_string($original_string, 6); </code></pre> <p>Note that this function doesn't check for uniqueness in the valid chars passed to it. For example, if you called it with a valid chars string of <code>'AAAB'</code>, it would be three times more likely to choose an A for each letter as a B. That could be considered a bug or a feature, depending on your needs.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload