Jump to content

PHP problems


Truman

Recommended Posts

Hi, I was hoping that you could help we with this problem.

First, I need to make $name variable with my name. After that, using knowledge of strlen(string), rand(min, max), and substr(string, start, length) I need to print a random character from my name. It's a codeacademy problem. So it shouldn't be a number, only one of letters of my name.

Link to comment
Share on other sites

Yes, I know how those functions work but I hit a snag.

This is one of the solutions that I've tried but it doesn't work:

 

$name = "milos";
$sub0 = substr($name, 0);
$sub1 = substr($name, 1);
$sub2 = substr($name, 2);
$sub3 = substr($name, 3);
$sub4 = substr($name, 4);
print rand($sub0, $sub4);

Link to comment
Share on other sites

Right, that's not going to work. You set $sub0 to "milos", $sub1 to "ilos", $sub2 to "los", etc, and $sub4 to "s". Then you're passing "milos" and "s" to the rand function. The rand function takes numbers, not strings. You didn't use the strlen function there, you need to use that. Figure out how many characters there are, use that length with rand to get a random number that is in the length, and then use the random number with substr.

Link to comment
Share on other sites

In one of my previous efforts this is what I wrote:

$name = "milos";
$length = strlen($name);
print rand(0, $length);

 

I don't know how and why should I use a random number with substring. For previous code I receive a message "The random output you printed from your name should be a letter."

Link to comment
Share on other sites

There is only one class definition with only one constructor, you can make as many instances of the class as you want without making any change to the class. You probably should make a different thread for this since it's completely unrelated to the topic.

  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...