Categories
PHP

Repeat and Shuffle a String

How to use str_repeat() function to repeat a string a given number of times. You’ll also learn to shuffle a string to create a password generator.

  1. str_repeat()
  2. str_shuffle()
  3. Create a strong password generator

Repeat a string

<?php
 //Syntax
 str_repeat(string $string, int $times): string

This function has two parameters:

  1. $string the input string.
  2. $times the number of times the input string should be repeated.

Example:

<?php
 echo str_repeat('-', 10);
 //Prints: ----------

 echo str_repeat('hi ', 3);
 //Prints: hi hi hi 

Nothing will prints if the $times is set to 0.

<?php
 echo str_repeat('-', 0);
 //Prints nothing

Shuffle a string

<?php
 //Syntax
 str_shuffle(string $string): string

This function returns the shuffled string, see example;

<?php
 echo str_shuffle('Hello World');
 //lelold orWH
 //WlHl odlero

You can use str_shuffle() function to generate strong passwords.

Create a strong random length password generator

<?php
 $a = str_shuffle('abcdefghijklmnopqrstuvwxyz');
 $A = str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ');
 $n = str_shuffle('0123456789');
 $x = str_shuffle('!"#$%&\'()*+,-./:;<=>?@[\]^_`{|}~');
 $all = str_shuffle($a.$A.$n.$x);
 
 $min = 12; #Minimum password length
 $max = 24; #Maximum password length
 $len = rand($min, $max); #Random password length
 
 $_init  = substr($a, 0, 1); #Include a lowercase letter
 $_init .= substr($A, 0, 1); #Include an uppercase letter
 $_init .= substr($n, 0, 1); #Include a numeric character
 $_init .= substr($x, 0, 1); #Include a symbol

 $_init .= substr($all, 0, $len);

 $password = str_shuffle($_init);
 echo $password;
 //Prints shuffled password with random length
 //For example: Q:KaDUiXE,{SYPuZ~>p09

Working with Strings: