Reputation: 1876
I am being passed an array by an identity management system (SAML2.0 based) which provides me a set of user attributes in an array.
The identity provider configures the structure of this data, and I am providing this (much larger company) with a service. Altering the way I receive this array is not in my control.
The array arrives with me in this form (this is what I see if I print_r
the array):
Array
(
[http://longurl/surname] => Array ([0] => Smith)
[http://longurl/firstname] => Array ([0] => John)
);
As you can see, the keys to this array of arrays is a URL (I'm sure they have a good reason?!). However if I try to work with this array like so:
echo 'Hello Mr. '.$SAMLDATA[http://longurl/surname][0];
This is no good, because colons aren't valid characters inside variables (or so I read).
Escaping the character doesn't seem to work, any idea what I can do here? Many thanks.
Upvotes: 2
Views: 343
Reputation: 270609
Since PHP's non-integer array keys are strings, they must be quoted as strings. If you do not quote them, PHP will issue an E_NOTICE
about undefined constants, assuming you meant to use a string in place of the constant, and if you attempt to use an array key with a colon like those URLs, it will likely result in a fatal syntax error.
So to fix your issue, you really only need to correctly quote the array keys as in:
echo 'Hello Mr. '.$SAMLDATA['http://longurl/surname'][0];
Note that the only circumstance in which it is acceptable not to quote string array keys is when interpolated inside a double-quote string. For example:
$str = "This double-quoted string has an $array[key] value inside it";
For simple array values like the above, you need not quote the key in a double-quoted string.
However, in your case, you will probably need to use the {}
syntax to access one of these URL keys in an interpolated string. When using {}
you will need to quote the string array keys. Generally I always recommend using the {}
syntax for array and object values, as it improves readability:
// When using {} enclosures, you do need to quote the key
$str = "This double-quoted string has an {$array['key']} value inside it";
The various rules surrounding the above examples in double-quoted strings are documented here.
Upvotes: 1