views:

256

answers:

1

How can i include a variable and make it part the string.

header("Location: http://www." . "$_SESSION['domainname']");

The above code doesn't work.

+3  A: 

The reason why your code didn't work is due to how PHP handles indexed arrays inside strings. You had:

"$_SESSION['domainname']"

But what PHP wanted to see was:

"$_SESSION[domainname]"

No single quotes this time. You only omit those single quotes if you are referencing a variable directly inside a string.

Note that string interpolation, such as this, can work with simple arrays ("$a[x]") but not with arrays of arrays ("$a[x][y]") unless you use curly braces ({$x}, {$a['x']['y']}; note the single quotes in the curly braces--they aren't exactly like PHP's normal string interpolation, but rather more like referencing a variable elsewhere in PHP).

Peter
So it doesn't interpret it as a constant if i remove the single quotes from inside the brackets?
Codex73
What worked: header("Location: http://www.$_SESSION[domainname]");
Codex73
No, it won't interpret it as a constant as long as you are referencing the array index inside a string. Outside a string, it would assume domainname is a constant.
Peter