emporio emporio - 6 months ago 24
PHP Question

Random password generator in PHP not returning password

I am trying to set up a random password generator function in php but this is not working for me. I get the error:


Notice: Array to string conversion in C:\xampp\htdocs\php-testing\index.php on line 12

Array


What am I doing wrong?

<?php
function pwGenerator($len = 10) {
$charRange = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789!@#$%^&*()";
$pw = array();
$length = strlen($charRange);
for ($x = 0; $x < $len; $x++) {
$n = rand(0, $length);
$pw[] = $charRange[$n];
}

return $pw;
}

echo pwGenerator();

Answer

You cannot convert array into string directly. So instead of storing it in array you can attach characters with a string. and now it is working.

<?php
    function pwGenerator($len = 10) {
        $charRange = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789!@#$%^&*()";
        $pw = null;
        $length = strlen($charRange);
        for ($x = 0; $x < $len; $x++) {
            $n = rand(0, $length);
            $pw .= $charRange[$n];
        }
        return $pw;
    }
    echo pwGenerator();
    ?>