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);
asked Dec 5, 2016 at 22:26
2
  • 2
    You should take a stab at it and then if you get stuck, post again with your code. Commented Dec 5, 2016 at 22:28
  • Stack isn't a conversion service; try something first. Commented Dec 5, 2016 at 23:03

2 Answers 2

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);
answered Dec 6, 2016 at 0:47
Sign up to request clarification or add additional context in comments.

Comments

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);
answered Dec 5, 2016 at 23:33

1 Comment

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?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.