This forum is now read-only. Please use our new forums at discuss.codecademy.com.

Functions, Part I Forum

View Course » View Exercise

308 points
E69f934aaeff37b36c38202f597fe01f?s=140&d=retro
Submitted by
Lucky Singh
about 2 years ago

Need Explanation for 5/8

I got the code for this exercise from the forum itself, but I can't understand what's happening at line


<?php
// Use rand() to print a random number to the screen
print rand(0,10);
?>


<?php
// Use your knowledge of strlen(), substr(), and rand() to
// print a random character from your name to the screen.
$name='luckysingh';
$randomPosition=rand(0, strlen($name)-1);
$randomLetter=substr($name,$randomPosition,1);

print $randomLetter;
?>

Can you please explain me those highlighted lines in the above code. I really don't get it.


4 votes

permalink

$name="naib hossain khan";
print $name[rand(0,strlen(substr($name,0,strlen($name))))];

500 points
Picture
Submitted by
Naib Hossain Khan
about 2 years ago


2 votes

permalink

$name = 'Andy';
$length = strlen($name);

$namelength = rand(0,$length);

$namelength = $namelength - 1;


$solution = substr($name,$namelength,1);
echo $solution;

well i did it this way which is a bit less complex than the way you did it hopefully you will be able to figure it out when you look at this.

736 points
Picture
Submitted by
Andrew Dear
about 2 years ago

4 Comments

E69f934aaeff37b36c38202f597fe01f?s=140&d=retro Lucky Singh about 2 years ago

Thanks bro, your code was pretty easy to understand. Thanks!! :D

Picture Andrew Dear about 2 years ago

np :)

Picture Oskar Le about 2 years ago

thanks for the codes. I got mad and just typed print "a"; and passed....

55a5a341937676f15200024a_542488205 ColorfulPastels about 2 years ago

Thanks bro. You helped me a bunch.


1 vote

permalink

Thanks Andy. used your logic!

<?php
// Use rand() to print a random number to the screen
print rand (1,10)
?>


<?php
// Use your knowledge of strlen(), substr(), and rand() to
// print a random character from your name to the screen.
$name = "Ben";
$length = strlen($name);

$namelength = rand(0,$length);

$solution = substr ($name, $namelength,1);
echo $solution;
?>

738 points
Picture
Submitted by
Benjamin Yue
about 2 years ago


0 votes

permalink

$your name for ex="tamer";
$random charString for your name=rand(0,strlen($name)-1);//we use strlen($name)-1 to make random choice in side your name without going outside path your name for ex rand(0,strlen($name)) maybe choose 5 it well be Error substr($name,$ranpo,1) it will be error command
$cut char inyour name=substr($name,$ranpo,1);
print $cut car inyour name;

622 points
5588981076b8fe330d0002ae_486146267
Submitted by
Tamer Abu Laila
about 2 years ago