I've always used '{' and '}' to access characters in a PHP string.  I knew I could, but I never really used '[' and ']' to do the same, out of habit more than anything else.  Apparently, not only is it allowed, but it's recommended by the PHP documentation here.

"Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array-brackets like $str[42] so think of a string as an array of characters.  They may also be accessed using braces like $str{42} for the same purpose. However, using square array-brackets is preferred."

That's fine.  I'll probably still use the curly braces, only because it indicates the type of the variable I'm working with implicitly — a string.  I also have a feeling that this was not the case in PHP3, but I don't recall.  I don't know all of the legacy concerns in PHP; there are too many of them to count.  In any case, it has this "nice" side effect:

If you're passing an array of characters, i.e. array('x'), you can also pass just 'x,' and it still functions as if it were a 1 element array. Both sizeof(array('x')) as well as sizeof('x') return 1. Likewise, if you access the first element of the string 'x' using $var[0], it yields the same value as accessing the first element, $var[0], of an array('x').  Thus, if a function expects an array of characters, i.e. array('x','y','z'), we no longer have to pass in array('x') for a single element array, but can also pass in 'x.'

I'm not sure it's wise, just in terms of code clarity, to use language nuances like this.  The only reason I brought it up is that I saw it in someone else's code, and I had to stare at it for a few seconds before realizing he was using this particular nuance to get the job done.  I suppose it's logical, sort of.  A string isn't really an array of characters, though, and it at least merits a comment.  Personally, I prefer clarity, and I find it rather strange that sizeof('x') returns 1, but that sizeof(array()) returns 0.  Perhaps I'm biased by my strongly-typed language background, but I'd just pass in array('x').

Tell an amigo:
  • Sphinn
  • Digg
  • Reddit
  • del.icio.us
  • StumbleUpon
  • Facebook

Related posts:
ROTD: Replacing "Smart" Quotes with "Dumb" Quotes Microsoft applications have this nasty habit of exchanging both your...
RSS Made Even Simpler Syndication isn't only for blogs; it can be used for...
Checking for Dead Links Automatically This neat little class can return the HTTP status code...
Twitter vs. Capital One's Reputation. Twitter vs. "*" I have to admit, I underestimated the power of Twitter...
A (not so simple) method to add rel="nofollow" to links I wrote this script so that I can run it...