w3resource
php Programming Exercies

PHP String Exercises : Generate simple random password from a specified string

PHP String: Exercise-9 with Solution

Write a PHP script to generate simple random password [do not use rand() function] from a given string.

Sample string : '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcefghijklmnopqrstuvwxyz'
Note : Password length may be 6, 7, 8 etc.

Sample Solution:

PHP Code:

<?php
function password_generate($chars) 
{
  $data = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcefghijklmnopqrstuvwxyz';
  return substr(str_shuffle($data), 0, $chars);
}
  echo password_generate(7)."\n";
?>

Sample Output:

89Qp3AK

Flowchart :

Flowchart: Generate simple random password from a specified string

PHP Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a PHP script to format values in currency style.
Next: Write a PHP script to replace the first 'the' of the following string with 'That'.

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming