Meet My Friend, Mr. Curly Brace

The curly brace (also known as the curly bracket) is a fairly powerful tool in PHP.  In a nutshell, it lets you specify the name of a variable in a string.  Why is that so important?  Because what if you want to specify a member variable to an object in another variable?  Maybe an example would elucidate the problem...

Let's say you want to compare apples to oranges in a standard object...

$obj = new stdClass();
$obj->apples[] = "Granny";
$obj->apples[] = "Red";
$obj->apples[] = "Bad";

$obj->oranges[] = "Navel";
$obj->oranges[] = "Tangerine";

Now, let's say that you need to access either the apples array or the oranges array based on some other variable, $fruit


$fruit = "oranges";

As a shortcut, you can do this:

/*  Output:
   [0] => Navel
   [1] => Tangerine

But what if you needed to be more specific?  What if you needed to only access the first element of whichever fruit you chose?  The following does not work!


This is because php now thinks that $fruit is an array.  So how do you tell it to try to find the first element of oranges?  We have to consult with our old friend, Mr. Curly Brace.  Observe:

/* Output:

By placing the curly braces around our variable, $fruit, we are telling PHP to evaluate the variable inside the string.  We can then access that array's elements as we normally would.  In fact, we can even specify the name of the variable as a literal string like so:


Isn't that cool?  As a PS, here's another real quick use of the curly brace, which I use all the time, though I know it is generally frowned on:

print "My IP address is {$_SERVER["REMOTE_ADDR"]}!";

See what happened there?  I was able to specify, without breaking out of a string, an associative array.  As long as you wrap curly braces around it, it will work.  It is frowned on, by the way, because some say it makes the code harder to follow for other programmers.