Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP PHP Basics Daily Exercise Program Daily Exercise Program

Sahan Balasuriya
Sahan Balasuriya
10,115 Points

I tried doing it little differently..

So I tried to see if there is way to do this without using the if statement can someone check and tell me why this doesn't work. The console says undefined variable .

//store each excerice in a string variable
$exercise1 = 'display "Hello World!"';
$exercise2 = 'Convert Pounds to Kilograms';
$exercise3 = 'Convert Kilograms to Pounds';
$exercise4 = 'Convert Miles to Kilometers';
$exercise5 = 'Convert Kilometers to Miles';
$exercise6 = 'Month long string of the day';
$exercise7 = 'String of the day with levels';
//create a variable containing the day of the week
$day = date('N');
//use an if statement to test for the day of the week
$string = '$exercise' . "$day";
echo $$string;
//display the corresponding excercise string

2 Answers

Niki Molnar
Niki Molnar
25,698 Points

These two lines are causing the problem:

$string = '$exercise' . "$day";
echo $$string;

You can't use variables inside single quotes, only in double quotes, so this is OK:

echo "Hello $name";

Whereas, the following would cause an error:

echo 'Hello $name';

To work with single quotes, you need to use concatenation:

echo 'Hello ' . $name;

Your line with echo $$string; uses two $$

echo $$string      // Error
echo $string       // Compiles
Paulo Dacaya
Paulo Dacaya
32,900 Points

Maybe @Sahan Balasuriya was trying to achieve something like this.

$day = date('N');
$day = 6;

$string = 'exercise' . "$day"; 
//$string holds the variable 'exercise6'

echo $$string;
//echo $exercise6
//result: Month long string of the day

Issue: Added an extra '$' in the program when assigning to $string.