Manh Nguyen Manh Nguyen - 24 days ago 6
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]; // ä


DEMO

Can anyone tell me why?

UPDATED

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

Answer

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 ä.