-1

A total noob question, but here I go:

I have 3 arrays (numbers, the alphabet and other characters), the usual.

I need to basically come up with code that will create a random password. And I have to have the 3 arrays... how do I loop through them to get a character from each? I'm confused, please someone point me to the right direction. Thanks

Anna Kurmanova
  • 141
  • 1
  • 7

1 Answers1

0

So we will loop N times and pick out a rand value from each array you have

<?php
$length = 32; //length of random password 
$a1 = str_split('0123456789'); // convert to array
$a2 = str_split('%^*+~?!'); //convert to array
$a3 = str_split('abcdefghigklmnopqrstuvwxyz'); // convert to array

$result = ""; //final random password

for($i = 0; $i < $length; $i++){
    //choose random array from the three a1, a2, a3
    //then choose random value from the chosen array
    // note: array_rand is a built-in PHP function
    // that accepts an array as the first parameter
    // and number of random elements to pick out 
    // as a second optional parameter that defaults to 1
    $values = [$a1,$a2,$a3];
    $chosen = array_rand($values);

    $result .= $values[$chosen][array_rand($values[$chosen])];
}
 //print the result out
 echo $result;

?>

I hope this will help!

ArsanGamal
  • 158
  • 1
  • 10