Manh Nguyen Manh Nguyen - 1 year ago 75
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); // ä

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download