views:

215

answers:

4

I'm wondering if there is a shorter way of inserting text in PHP than

<?php
$city = "London";
?>
This website is a funky guide to <?php print $city; ?>!!!

For example, using ruby on rails, I could set

city = 'London'

somewhere in the code, and in my .erb file I could do

This website is a funky guide to <%= city %>!!!

I did read somewhere that {$city} could be used, but I tried it and it didn't. So is there a shorter form than <?php print $var; ?> ?

+2  A: 

If you switch out of PHP mode, then the only way to print the variable is to switch back into it and print it like you have above. You could stay in PHP mode and use the {} construction you tried:

<?php
$city = "London";
echo "This website is a funky guide to {$city}!!!";
?>
scompt.com
{} not necessary, they'll just print out around the variable.
Shadow
@Shadow : the {} won't be displayed ; and it's useful to include them, for the day you'll want to display some string just after the $city : "... guide to $cityhello" would not work ; "... guide to {$city}hello" would.
Pascal MARTIN
+5  A: 
Pascal MARTIN
can you say why using short_open_tag is not considered good practice? The article you link to says it can conflict with xml - is that the only reason or are there others?
Hamish Downer
Hi, I have just edited my post to add some informations / considerations about short open tags :-) It's a bit longer than what I wanted ^^ But I hope it'll help!
Pascal MARTIN
That's great :) Thank you
Hamish Downer
You're welcome :-) Have fun!
Pascal MARTIN
A: 

Just extend your PHP block and do this:

<?php
$city = 'London';
echo 'This website is a funky guide to ',$city,' !!!';
?>

Alternatively, you can use " " instead of ' ' and replace ',$city,' with $city, but it takes more CPU time to parse for variables.

Shadow
Shouldn't the , be dots?
blub
Not with echo. Echo can take an arbitrary number of arguments and its faster to pass multiple arguments than to concatenate.
Shadow
@blub : echo supports using ',' to separate data (as if it was a function-call ; but not necessarily with parenthses) ; see the examples on http://php.net/echo for instance
Pascal MARTIN
+1  A: 

I did read somewhere that {$city} could be used

If you go for a templating engine such as Smarty you can do this. That might be useful if you're developing in a team and some of them don't know PHP.

Otherwise, the shortest you will get is the following, assuming you have short tags enabled:

<?=$city?>

If you don't, or you're creating an app to redistribute to others, then use this:

<?php echo $city ?>
DisgruntledGoat