0

I want to display the character codes of a string in php.

<?php
$Text = '{"text":"سلام"}';
for($i = 0;$i < strlen($Text);$i++){
    echo mb_ord($Text[$i]),"<br>";
}
?>

But its output is null enter image description here

  • You're iterating byte by byte, which won't work for multibyte strings. Look at https://stackoverflow.com/q/2556289/476 for example… – deceze Feb 26 '21 at 08:43
  • 1
    `mb_ord($Text[$i])` makes little sense. The `mb_` functions are made to handle multibyte characters correctly - but by accessing the string value with `$Text[$i]`, you are _not_ accessing a character, you are accessing a single byte. If you just want the individual byte value for each position, then use `ord` instead. If you want the actual unicode code point from `mb_ord` – then see to it, that you actually access a _character_ frist. (Research it, if you don’t know how.) – CBroe Feb 26 '21 at 08:44

1 Answers1

2

You are trying to get all "bytes" of the unicode string. You need to use mb_strlen() to get the real length of the characters.

Then, you need to use mb_substr() to get the right character.

$Text = '{"text":"سلام"}';
for($i = 0; $i < mb_strlen($Text); $i++) {
    echo mb_ord(mb_substr($Text,$i, 1)), "<br>";
}

Output :

123
34
116
101
120
116
34
58
34
1587
1604
1575
1605
34
125

See also all mb_* functions

Syscall
  • 19,327
  • 10
  • 37
  • 52