The need for brackets


#1

Hi All,

I am still learning PHP and have a question about the use of brackets and variables.

$id = $_GET[“id”];
$name = $_GET[“name”];
echo “
” . $id . “: {$name}”;

When I originally wrote this I put brackets around both $id and $name, but received an error. I experimented with the brackets because I am still not sure when they are required and got it to work, but I don’t know why. Why would you not need brackets for both? Why does putting brackets around both produce an error? Thanks ahead for any explanation.

Jim


#2

If that echo was in a template, you would use them. You can use them in a query to indicate an array. Some coders use them to indicate a replacement variable. Not really sure why its giving you an error, it should just echo {$name}. What was the error message?


#3

Thanks for the fast reply.

When I change the code putting brackets around $id I get a syntax error.

    $id = $_GET["id"];
    $name = $_GET["name"];
    echo "<br /><strong>" . {$id} . ": {$name}<strong>";

Parse error: syntax error, unexpected ‘{’ in C:\xampp\htdocs\xxx\xxx.php on line 32

In this case I am passing the variable from an array. If I remove the brackets, no error.


#4

$_GET is an array, but you’re telling it what position to look at to get the info. You don’t need the brackets in this instance.


#5

Well, to explain… Did you look at the code? It’s so very simple!

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

PHP variables are $xyz or $id or $this_huge_variable_name_that_is_just_a_sample …

Now, strings are “blah blah blah” “some text or other stuff” “etc”

The code you posted is “
” a STRING!
plus . $id . A PHP VARIABLE! (concat’d to the string!)
plus “: {$name}”; a STRING!

You can put ANYTHING you can type in the last string… It’s a string!
$id is valid, {$id} Is not! Simple as that!

Also, your code is incorrect! You OPEN the , never close it

Hope this explains!

PS, Richei was correct, the brackets inside the string may have been from a template!

#6

Bah!
Thanks so much for this explanation. It makes it obvious and I was missing it.

Jim


#7

LOL, yep! Just a different viewpoint makes programming “puzzles” a bit simpler!

Glad you got it… CYA in the bitstream…