7

I was going through a codebase and came across a line I had a question about. It's something I haven't seen before and I was wondering if someone could explain it for me. Here's the code:

$variableName = $array[1];
$variableName{0} = strtolower($variableName{0});
$this->property = $variableName;

What are the curly braces being used for? I've used curly braces to define variables as variable names before, but is this the same thing? I can't seem to find any resources online that explain it, but I'm not sure if I'm searching for the right thing.

starbeamrainbowlabs
  • 5,692
  • 8
  • 42
  • 73
opes
  • 1,778
  • 1
  • 16
  • 22

3 Answers3

6

access the single byte with that index {0} => first char (in non-utf8 string)

you could simply test it with:

$var='hello';
echo $var{0};
dynamic
  • 46,985
  • 55
  • 154
  • 231
  • Interesting. A nice shortcut instead of substr() for a single character - provided you already know the length of the variable you are testing against. – opes Mar 23 '12 at 18:04
  • 1
    I would avoid it anyway. Because if you will use multibyte string you get malformed string. Look at mb_strlen if you need to access single chars (using UTF-8) – dynamic Mar 23 '12 at 18:07
  • [One more reason](https://wiki.php.net/rfc/deprecate_curly_braces_array_access) to avoid it, as it will be deprecated from 7.4. – Déjà vu Dec 26 '19 at 18:23
3

It's setting the first character of the string to lower case. It's a string shortcut operator, functioning the same as this:

<?php
$variableName = strtolower(substr($variableName, 0, 1)) . substr($variableName, 1)
landons
  • 9,502
  • 3
  • 33
  • 46
  • So essentially, just lcfirst() then? Provided the variable is a string. – opes Mar 23 '12 at 18:03
  • 1
    Lol. Yeah, I've never had a use for that function, so I didn't know there was one dedicated. But yes, that's the one. – landons Mar 23 '12 at 18:09
3

Curly braces {} work the same as square brackets [], for array or string indexing. I'm guessing it is borrowed from perl, in which the square brackets are used for arrays and braces are used for hashes. But in PHP arrays and hashes are the same thing.

Brian
  • 15,599
  • 4
  • 46
  • 63