Clover
Clover

Reputation: 5

How to add random array value to each character?

I want to add random array values to each character

<?php
//array_rand ( array $array [, int $num = 1 ] ) 
$input = array("1","2","3");
$rand_keys = array_rand($input, 2);
$random = $input[$rand_keys[0]];
$str = "ABCDEFG";
$newstr = substr_replace($str, $random, 1, 0);
echo $newstr
?>

Expectation :

ABCDEFG = A1B3C1D2E3F2G

Upvotes: 0

Views: 24

Answers (1)

Niklesh Raut
Niklesh Raut

Reputation: 34914

You can do it using foreach, Added random number after each character from given set of number or array element.

<?php
$str = "ABCDEFG";
$randomNumber = [1,2,3];
$strArr = str_split($str);
$strWithRandomNumber = "";
foreach($strArr as $str){
    $strWithRandomNumber .= ($str.$randomNumber[array_rand($randomNumber,1)]);
}
echo $strWithRandomNumber;
?>

Live Demo: http://sandbox.onlinephpfunctions.com/code/e5a60fe5f42bb0e4afcaa2df4ffefe2b0974685a

Output example:

A2B3C1D2E2F2G2

Upvotes: 1

Related Questions