0

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

1
  • why did you remove last number for character G ? it should be A*B*C*D*E*F*G* where * will be any number from [1,2,3] Commented May 8, 2021 at 3:40

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Happy Coding. Be safe and healthy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.