Home » Php » Javascript function in PHP fromCharCode()

Javascript function in PHP fromCharCode()

Posted by: admin July 12, 2020 Leave a comment

Questions:
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?

How to&Answers:

Try the chr() function:

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

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

Answer:

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;});
    }
}

Answer:

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;
    } 

Answer:

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);

Answer:

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));

Answer:

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: