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

Functions, Part I Forum

View Course

65 points
Df0f685d3ab1bedf477204b23dda24ff?s=140&d=retro
Submitted by
MartG.
over 1 year ago

stuck on 5/8 getting error " The random output you printed from your name should be a letter. "

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

$s = substr("marta", 0, 2);
echo $s;
?>
rand(0,2) outputs number, tried everything and cannot fix it, help anyone?


0 votes

permalink

the last parameter in substr function is how many substrings it will display:
substr($name, $letter, #to display);

you can use $letter = rand(0, $length); This will pick a random letter within the substring szie.

81 points
Picture
Submitted by
Blake Turner
over 1 year ago

2 Comments

Df0f685d3ab1bedf477204b23dda24ff?s=140&d=retro MartG. over 1 year ago

Thanks,
I tried:
$letter = rand(0, $length);
echo $letter;

and it still outputs a random number though... maybe the error is somewhere else then?

Picture Blake Turner over 1 year ago

My mistake.

The strlength will display how many characters are in a string.
"Blake" will display 5 if I were to print the length.
1 = B; 2 = l; etc..

substr will iterate a string into parts. It however will consider position 0 as well. So when I use the string "Blake" it will put characters in order of:
0 = B; 1 = l; etc...

This means this if you rand(0, $length) it will make a random number 0-5 which would be 6 characters (0, 1, 2, 3, 4, 5). to fix this we can do:

rand(0, $length - 1)