Tag Archives: Hello world program

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 “/”.