views:

27

answers:

1

I'm trying to get a constant string and index it as if it was an array of characters (square bracket syntax). When I try this code it fails on the last line.

define( 'CONSTANT_STRING','0123456789abcdef');
echo CONSTANT_STRING; // Works by itself :)
$string = CONSTANT_STRING;
echo $string[9]; // Also works by itself.
echo strlen(CONSTANT_STRING); // Also works by itself.

echo substr(CONSTANT_STRING, 9, 1); // Ok, yes this works, but not as clean.

echo CONSTANT_STRING[9]; // Fails as a syntax (parse) error.

I am using a constant string like this in a function. Since it could be called multiple times on one page it really should be a constant. What is the best option if there is no way to do this like I originally intended.

+2  A: 

PHP Constants can only be scalar values, so the engine doesn't try to properly parse a constant that's used as something more than a scalar, like an array or an object.

This is a problem in your case because the brackets are used to point at an array index and can be used as a shortcut to grab a character at a specific location in the string.

You'll just have to do it the "hard" way and use substr().

Charles