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:

function password_generate($chars) 
  $data = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcefghijklmnopqrstuvwxyz';
  return substr(str_shuffle($data), 0, $chars);
  echo password_generate(7)."\n";

Sample Output:


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?

Test your Programming skills with w3resource's quiz.

Share this Tutorial / Exercise on : Facebook and Twitter

PHP: Tips of the Day

PHP: PHP function overloading

You cannot overload PHP functions. Function signatures are based only on their names and do not include argument lists, so you cannot have two functions with the same name. Class method overloading is different in PHP than in many other languages. PHP uses the same word but it describes a different pattern.

You can, however, declare a variadic function that takes in a variable number of arguments. You would use func_num_args() and func_get_arg() to get the arguments passed, and use them normally.

For example:

function myFunc() {
    for ($i = 0; $i < func_num_args(); $i++) {
        printf("Argument %d: %s\n", $i, func_get_arg($i));

Argument 0: a
Argument 1: 2
Argument 2: 3.5
myFunc('a', 2, 3.5);

Ref : https://bit.ly/2WnjWAt