Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,575 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.