PHP constant bracket indexing

I am trying to get a constant string and index it as if it were an array of characters (square bracket syntax). When I try this code, it does not work 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 use a constant similar to this function. Since it can be called several times on the same page, it really needs to be a constant. What is the best option if there is no way to do this as I originally planned.

+4
source share
1 answer

PHP constants can only be scalar values, so the engine does not try to correctly analyze the constant, which is used as something more than a scalar, as an array or object.

This is a problem in your case, because the brackets are used to indicate the index of the array and can be used as a shortcut to capture a character at a specific place in the string.

You just need to do it in a "hard" way and use substr () .

+4
source

Source: https://habr.com/ru/post/1313821/


All Articles