printing out 1 random letter of a word php functio

2019-06-10 05:26发布

问题:

This question already has an answer here:

  • a method of selecting random characters from given string 15 answers

i want to Use strlen(), substr(), and rand() to print a random character from my name to the screen.

<html>
<p>
<?php
// Use strlen(), substr(), and rand() to
// print a random character from my name to the screen.
$name = "jordi";

$length = strlen("$name");
$length = rand();
$partial = substr($lengt, 0,5);

print $name. "<br />";
print $length. "<br />";
print $partial. "<br />";
?>
</p>
</html>

the outcomes right now(the numbers are randomly generated ofcourse):

jordi

9286122

92861

can someone help me with this.

回答1:

Here are the steps using all of the functions required by your assignment -

$nameLength = strlen($name); // gets the length of the name
$randomNumber = rand(0, $nameLength - 1); // generates a random number no longer than the name length
$randomLetter = substr($name, $randomNumber, 1); // gets the substring of one letter based on that random number
echo($randomLetter);


回答2:

$name = "jordi";
$rndCharIndex = rand(0, strlen($name) - 1);  // random character index for the string
$rndChar = $name[$rndCharIndex];  // Look up the character in that random index
echo $rndChar;