Jump to content

Recommended Posts

Hello All:

 

I have a newb question here. In learning php I seem to notice that we use the Curly Braces for the IF/ELSE statements but I have seen them used to seperate variables in like

 

   echo "<b>" . $id . ": {$name} </b>";

 

now $name is a variable and I think I understand why it my be like that but in leaning from a book, I am a bit confused as to why the author decided to throw that line together that way?

 

Any thoughts or advice would be appreciated.

 

Paul

Link to comment
https://forums.phpfreaks.com/topic/82851-solved-when-do-you-use-curlies/
Share on other sites

Wrapping variables in curly braces does have it's uses, curly braces are not just for defining code blocks. Curly braces are normally used when echoing a variable which is an array within a string, eg:

echo "$my_arr['some_key'] bla bla bla";

The above code will result in an error, however if you wrapped the variable within braces the code will work fine:

echo "{$my_arr['some_key']} bla bla bla";

To elaborate on what wildteen said, using the curly braces is also known as complex syntax, not complex because of the syntax itself but because you can make complex expressions.

 

Here is another instance where you'd want to use curly braces around the variable name:

<?php
$fruit = 'banana';
echo "John has two $fruits"; // won't work, PHP will look for a variable called $fruits
echo "John has two {$fruit}s"; // works, PHP will look for a variable called $fruit
?>

 

Like roopurt I generally use curly braces around ALL variables which are inside strings for two reasons:

1) I think it looks nicer.

2) It ensures that it will always work (see wildteen's and my example).

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.