1

Can anyone help me convert this javascript function to php?

var t='[{"id_page":14,"in_visible":1,"in_insert":1,"in_update":1}]';
function hash (s) {
  return s.split("").reduce(
      function(a, b) {
        return a = (a << 5) - a + b.charCodeAt(0),  a & a  
      }, 0
  ).toString()
}
            
alert(hash(t));

I'm trying this php script:

function fun($a, $b)
{
    return $a = ($a << 5) - $a + ord(substr($b,0,1));//  $a & $a;
}

$v = '[{"id_page":14,"in_visible":1,"in_insert":1,"in_update":1}]';
$a = str_split($v);
$r = array_reduce($a,'fun',0);
print_r($r);
Erlen
  • 121
  • 1
  • 12

2 Answers2

1

The problem with your code: Although in JS all numbers are 64-bit floating point values, the bitwise operators like shifts and bit and,or operate on 32-bit integers. Thats why 32-bit integer overflow is happening in your JS function, but in PHP function this doesn't happen.

To fix it: you need to simulate integer overflow in the PHP function to achieve same outputs as from JS. This has already been done in this answer to a different question. This function needs to be applied on every binary operator. In your case the << and & (it seems like a & a in your js function is used purely to make a 32-bit integer out of the result).

So the PHP function returning same hashes could look like this:

<?php
function intval32bits($value){
    $value = ($value & 0xFFFFFFFF);
    if ($value & 0x80000000)
        $value = -((~$value & 0xFFFFFFFF) + 1);
    return $value;
}

function fun($a, $b){
    return intval32bits(doOverflow32b($a << 5) - $a + ord($b[0]));
}

$v = '[{"id_page":14,"in_visible":1,"in_insert":1,"in_update":1}]';
$a = str_split($v);
$r = array_reduce($a,'fun',0);
print_r($r);
Community
  • 1
  • 1
Ko Cour
  • 929
  • 2
  • 18
  • 29
0

I got

function fun($a, $b)
{
    $a = $a & $a;
    return $a = ($a << 5) - $a + ord(substr($b,0,1));//  $a & $a;
}

$v = '[{"id_page":14,"in_visible":1,"in_insert":1,"in_update":1}]';
$a = str_split($v);
$r = array_reduce($a,'fun',0);
print_r($r);
Erlen
  • 121
  • 1
  • 12
  • Are you posting this as an answer to your own question? I don't think this will give a same result as your js function. Maybe you wanted to edit your question? – Ko Cour Dec 06 '16 at 00:26