9
var test = String.fromCharCode(112, 108, 97, 105, 110);
document.write(test);

// Output: plain

Is there any PHP Code to work as String.fromCharCode() of javascript?

LIGHT
  • 5,604
  • 10
  • 35
  • 78
  • http://blog.stanislavstankov.com/2010/02/equal-function-string-fromcharcode-in-php/ – Leniel Maccaferri Oct 20 '12 at 16:06
  • 2
    You [first asked `String.charCodeAt`](http://stackoverflow.com/questions/12989697/using-php-to-find-unicode-of-a-character) and now you're asking for the reverse? – Alvin Wong Oct 20 '12 at 16:06
  • [**This**](http://stackoverflow.com/questions/6058394/unicode-character-in-php-string) is what you want, because `String.fromCharCode` is basically UTF-16 – Alvin Wong Oct 20 '12 at 16:10
  • 1
    This works better then the posted answers `IntlChar::chr(31337)` – Lime Jul 15 '17 at 20:30

6 Answers6

8

Try the chr() function:

Returns a one-character string containing the character specified by ascii.

http://php.net/manual/en/function.chr.php

techfoobar
  • 65,616
  • 14
  • 114
  • 135
6

PHP has chr function which would return one-character string containing the character specified by ascii

To fit your java script style you can create your own class

$string = String::fromCharCode(112, 108, 97, 105, 110);
print($string);

Class Used

class String {
    public static function fromCharCode() {
        return array_reduce(func_get_args(),function($a,$b){$a.=chr($b);return $a;});
    }
}
Baba
  • 94,024
  • 28
  • 166
  • 217
2

The live demo.

$output = implode(array_map('chr', array(112, 108, 97, 105, 110)));

And you could make a function:

function str_fromcharcode() {
    return implode(array_map('chr', func_get_args()));
}

// usage
$output = str_fromcharcode(112, 108, 97, 105, 110);
xdazz
  • 158,678
  • 38
  • 247
  • 274
2

Try something like this..

 // usage: echo fromCharCode(72, 69, 76, 76, 79)
    function fromCharCode(){
      $output = '';
      $chars = func_get_args();
      foreach($chars as $char){
        $output .= chr((int) $char);
      }
      return $output;
    } 
Amitd
  • 4,769
  • 8
  • 56
  • 82
1

The chr() function does this, however it only takes one character at a time. Since I'm not aware of how to allow a variable number of arguments in PHP, I can only suggest this:

function chrs($codes) {
    $ret = "";
    foreach($codes as $c) $ret .= chr($c);
    return $ret;
}
// to call:
chrs(Array(112,108,97,105,110));
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

Use chr() if you only need ASCII support.

echo chr(120); // outputs "x"

Or its multi-byte twin mb_chr() if you need Unicode (requires mbstring extension):

echo mb_chr(23416); // outputs "學" 

See:

e1v
  • 627
  • 4
  • 7