13

Possible Duplicate:
How to get code point number for a given character in a utf-8 string?

I have a sample code in javascript:

var str = "HELLO WORLD";
var n = str.charCodeAt(0);

This returns 72

How do I make this done in PHP?

Community
  • 1
  • 1
LIGHT
  • 5,604
  • 10
  • 35
  • 78

4 Answers4

14

ASCII

This will help:

//Code to Character
echo chr(65);

//Character to Code
echo ord('A');

Unicode

But since these function work for ASCII, for Unicode:

function uniord($u) {
    $k = mb_convert_encoding($u, 'UCS-2LE', 'UTF-8');
    $k1 = ord(substr($k, 0, 1));
    $k2 = ord(substr($k, 1, 1));
    return $k2 * 256 + $k1;
}

echo uniord('ب');
M. Ahmad Zafar
  • 4,881
  • 4
  • 32
  • 44
6

The equivalent of the above would be

$str = "HELLO WORLD";
$n = ord($str[0]);
scottlimmer
  • 2,230
  • 1
  • 22
  • 29
6

Check this contributed note in the docs here:

http://www.php.net/manual/en/function.ord.php

There's a function which returns the UTF-8 value, which is what I assume you want.

AndreKR
  • 32,613
  • 18
  • 106
  • 168
David John Welsh
  • 1,564
  • 1
  • 14
  • 23
1

To be unicode aware you should try this one (http://us.php.net/manual/en/function.ord.php)

function uniord($u) {
    $k = mb_convert_encoding($u, 'UCS-2LE', 'UTF-8');
    $k1 = ord(substr($k, 0, 1));
    $k2 = ord(substr($k, 1, 1));
    return $k2 * 256 + $k1;
} 
Sven
  • 132
  • 1
  • 10