This is just a quick tip, something quite basic but hopefully useful to you.
Did you know you can easily include variable values in a PHP echo string?
It works as long as you’re using double quotes to surround the string. So, you don’t have to do this:
1 2 3 |
$name = "Rover"; echo "My dog is called " . $name . " and he's great!"; // Outputs: My Dog is called Rover and he's great! |
You can use:
1 2 3 |
$name = "Rover"; echo "My dog is called $name and he's great!"; // Outputs: My Dog is called Rover and he's great! |
Contrast:
1 2 3 |
$name = "Rover"; echo 'My dog is called $name and he's great!'; // Outputs: Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' |
Oops! This one’s giving us an error. Why? The string is being terminated too early with the apostrophe on “he’s”. So we’d have to escape it:
1 2 3 |
$name = "Rover"; echo 'My dog is called $name and he\'s great!'; // Outputs: My Dog is called $name and he's great! |
But this isn’t what we want, so we’re back to the beginning with concatenating (joining together) the string with the variable.
So, Option 2 is really our best bet.
Note this even works with more complex variable access such as the following:
1 2 3 |
$days = array('Sunday', 'Monday', 'Tuesday'); echo "Today is $days[1]"; // Outputs: Today is Monday |
Or:
1 2 3 |
$days = (object) array('day0'=>'Sunday', 'day1'=>'Monday', 'day2'=>'Tuesday'); echo "Today is $days->day1"; // Outputs: Today is Monday |
Find out more about the PHP string data type.
Discover more from Gavin Orland
Subscribe to get the latest posts sent to your email.
Comment: