Math Functions Part I 5/8


#1

Been hung here for a while with the following error:

Parse error: syntax error, unexpected T_VAR on line 12

Have tried moving the code around, changing the php tags, etc - it just doesn't like me starting a line with 'var'

Here's my code:

<html>
<p>
<?php
// Use rand() to print a random number to the screen
print rand(0, 20);
?>
</p>
<p>
<?php
// Use your knowledge of strlen(), substr(), and rand() to
// print a random character from your name to the screen.
var $name = "Daniel";
var $length = strlen($name);
var $rand = rand(0, $length - 1);
var $letter = substr($name[$rand]);
?>
</p>

Anyone know a work-around? Just seems like an endless site glitch.


#2

Take out var because in php you declare variables using "$".
Your substr has wrong parameters. Note that substr function allows you to return a piece of your string.
substr(string, start, length)
You forgot to include where it wants to start from your string and the amount of characters you want it to parse.

The code works with the following:

$name = "Daniel";
$length = strlen($name);
$rand = rand(0, $length - 1);
$letter = substr($name,$rand, 1);
print $letter;


#3

Thanks! Shouldn't be switching between courses like this.


#4

if i may come with an input.
try to make it on a few lines as possible. Great to cut it out and define the variables.
but afterward try to optimize the code. Might as well start now :slightly_smiling:

So the code COULD be like

$name = 'Daniel';

                   $name,      $rand,     length
print substr($name, rand(0,strlen($name)-1), 1);

Dont take it the wrong way, but if you can store it in a variable then you should be able to throw it directly into the function, unless you need it stored for something else.