Manh Nguyen Manh Nguyen - 5 months ago 31
PHP Question

Access character in a string with square braces doesn't output correctly

I have a string and i want to access

character. But it outputs question mark instead of correct character.

Here is my code.

$array = array('ä', 'b', 'c');
$string = 'äbc';
echo $string; // äbc
echo '<br />';
echo $string[0]; // ?
echo '<br />';
echo $array[0]; // ä


Can anyone tell me why?


echo strlen($string); // returns 4
echo mb_substr($string, 0, 1); // ä


Depending on your charset, the letter ä is a multi-byte letter. When you access a string using array access, it returns the first byte. In case of a multi-byte ä the returns a non printable control character.

Accessing the array using array-access returns the first element, regardless of it's length, in this case the multi-byte ä.