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

Functions, Part I Forum

View Course » View Exercise

520 points
4d4c57a05a89af9ae9f4f43f0ce58f3c?s=140&d=retro
Submitted by
andry007
over 2 years ago

"length - 1"

Why we need to use "length - 1"?
I used:
$myName = "Nick";
$nameLen = strlen($myName);
$nameRan = rand(0, $nameLen);
$nameRez = substr($myName, $nameRan, 1);
print $nameRez;

And it works! Without "length - 1".


2 votes

permalink

rand() return random number between min and max (inclusive),
substr() return part of a string "LIKE" an array ->

Starting from 0 index <-------> N is 0, i is 1, c is 2 and k is 3;
So possible indexes are 0,1,2,3...not 4,not 5 and even 6..

If $nameRan is 4 you get a null string because it's out of index...try this
you'll get a null string

$myName = "Nick";

$nameLen = strlen($myName);
print "nameLen: " . $nameLen . "<br \>";

$nameRan = rand(0, $nameLen);
print "nameRan: " . $nameRan . "<br \>";

// replaced $nameRan with 4, don't look at nameRan print
$nameRez = substr($myName, 4, 1);
print "nameRez: " . $nameRez . "<br \>";

That's why it's important to use length - 1
otherwise you could get a null string.

$nameLen = strlen($myName) - 1;   // fix
$nameRez = substr($myName, $nameRan, 1); // restored $nameRan

Hope I helped you

389 points
8f5e04999455007353ac19168968a2b7?s=140&d=retro
Submitted by
flaviusburghila
over 2 years ago