The need for brackets

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

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?

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.

$_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.

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!

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

Jim

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

Glad you got it… CYA in the bitstream…

Sponsor our Newsletter | Privacy Policy | Terms of Service