A PHP char_at function

PHP FAQ: Is there a PHP char_at or charAt function, like there is in other languages?

No, there isn't, but you can easily mimic a PHP charAt function like this:

$char = $my_string{4};

That's equivalent to having a charAt function like this:

$char = charAt($my_string, 4);

or this:

$char = char_at($my_string, 4);

A PHP char_at function

Now, if you really prefer a PHP char_at function over the PHP syntax shown above, feel free to use this PHP char_at function, which I just created for a project I'm working on:

function char_at($str, $pos)
{
  return $str{$pos};
}

While it's probably better to learn the PHP string syntax shown above (the curly braces), this char_at function is also a nice convenience method.

 

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.