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);
-
2You should take a stab at it and then if you get stuck, post again with your code.Jordan Soltman– Jordan Soltman2016年12月05日 22:28:16 +00:00Commented Dec 5, 2016 at 22:28
-
Stack isn't a conversion service; try something first.Funk Forty Niner– Funk Forty Niner2016年12月05日 23:03:31 +00:00Commented Dec 5, 2016 at 23:03
2 Answers 2
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);
Comments
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);