What does this do?

Hi all, I have been learning PHP pretty intensely for the last six months or so and now have a very good understanding of the language. I’ve taken a look at a script online and see something I have not seen before and wonders what it does. Please see below for the code:

while($string{$length} != " "): //What does the {$length} do? Never seen curly braces used in this way before...
                $length--;
            endwhile;

Any help or advice is appreciated as always :slight_smile:

When you use brackets or braces with a string it returs the character at that position; the string is treated like an array of characters.

$string = "Hello World!";

// both of these echoes the character 'H'
echo $string[0];
echo $string{0};

Looking at your snippet of code, assuming $string is a string and $length is it’s length, it begins at the end of the string and then steps back one character per iteration until it finds the last space.

Everywhere except when the { immediately follows the end of a variable name {$length} would be considered to be identically equal to $length (wrapping a variable name inside {} makes no difference to the variable name itself other than to keep it separate from any adjacent text that might be confused as being a part of that variable name). To actually wrap the variable inside {} you’d need to specify {{$length}}


$string = "bus";
$length = 2;

$bus = $string{$length};
// gives: s 

as adequately described above, a demonstration of how the string “bus” is made up of 3 elements (which start with a key of [0]) so item [2] is the letter s

Hey chaps, thanks for the info, makes a lot of sense, just had no idea what it was, not something I had seen before! Enjoy your morning/evenings! :slight_smile: Thanks again!