Is there any equivalent function that returns the character at position `X` in PHP?

You can use: $myString[20]


There are two ways you can achieve this:

  1. Use square brackets and an index to directly access the character at the specified location, like: $string[$index] or $string[1];

  2. Use the substr function: string substr ( string $string , int $start [, int $length ] )
    See http://us2.php.net/manual/en/function.substr.php for further informations.


To point out a small caveat I noticed on the Strings page of the manual:

Warning Internally, PHP strings are byte arrays. As a result, accessing or modifying a string using array brackets is not multi-byte safe, and should only be done with strings that are in a single-byte encoding such as ISO-8859-1.

The str_split() function can break a string into an array of each of its characters (or specific-length substrings), but also does not handle multi-byte strings. However, the user comments on there offer some potential solutions.

Tags:

Php

String