Powerful PHP: Less Known String Manipulation

Yet another thing that’s great in PHP is the power you have when doing some string manipulation/operation. Here’s something that is really useful, but I think it remains a bit unknown. Let’s imagine you need to take the first (or whatever) character of a string. Most developers go to the obvious:

$str = 'hello world';
echo substr($str, 0, 1); // outputs "h"

But here’s something better and cleaner.

echo $str{0}; // outputs "h"

This code chunk return the first character of $str, but it can be used with the same success for any other character of the string. In my opinion this is more cleaner and its really syntactically self documented.

This approach can be useful when trying to check whether the first symbol for instance is “?” or “/”.

7 thoughts on “Powerful PHP: Less Known String Manipulation

  1. You can also do this with de []’s, like: $str[0];

    Also, when checking if a string is longer then, let’s say 32 characters, if($str[33]) is faster then if (strlen($str) > 32)!

  2. That will also throw a warning if the key does not exist.

    if(array_key_exists(33, (array)$string)){ … }

    I’m not convinced that if($string[33]) … is faster than if(strlen($string) > 32) { … }

  3. @Jason Ok, I double checked it it just to be sure. I found some interesting things actually.

    The $str[33] method is faster. But, as you mentioned, It’ll give you a notice if the string is shorter. So you want to put a @ in front of it to ignore that notice.. But this actually makes it slower for some reason! Even if you don’t produce an error!

    My test:
    String: ‘abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz’;
    length: 52

    strlen(): 0.784919977188…
    [] : 0.502612113953…
    @[] : 1.37400698662…!!
    {} : 0.206066131592…

  4. substr($s, 0, 1) and $s[0] give you the first byte, which may not be a complete character. $s = “ɥello”;

  5. Tom says:
    August 18, 2011 at 5:06 pm

    Also, when checking if a string is longer then, let’s say 32 characters, if($str[33]) is faster then if (strlen($str) > 32)!

    Yikes! This isn’t binary safe! What if the 33 byte is a binary zero?

Leave a Reply

Your email address will not be published. Required fields are marked *