Can anyone help me with a solution that pulls the position and value of a random character from a given string using PHP. For example I have a a string variable $string = \
Code:
$string = 'helloworld';
$position = rand(0, strlen($string));
$character = $string[$position-1];
echo $character . ' is placed ' . $position . ' in the following string: ' . $string;
Output Example:
e is placed 2 in the following string: helloworld
CodePad Demo
Using mt_rand(),
You can get the index of a random character by:
$charIndex = mt_rand(0, strlen($string)-1);
$char = $string[$charIndex]; // or substr($string, $charIndex, 1)
$string = 'helloworld';
//generate a random position between 0 and string length ( note the -1 )
$randPos = mt_rand(0, strlen($string)-1);
echo 'Position : ' . $randPos . "\n";
echo 'Character : ' . $string[$randPos] . "\n";
$str = 'helloworld';
$randomChar = $str[rand(0, strlen($str)-1)];
CodePad.
$name = "Hello";
echo $name[rand(0,strlen(substr($name,0,strlen($name)-1)))];
You can use the rand($x,$y)
function which returns a random number between $x
and $y
inclusive:
$str = 'helloworld';
// get a random index between 0 and the last valid index
$rand_pos = rand(0,strlen($str)-1);
// access the char at the random index.
$rand_chr = $str[$rand_pos];