-1

I have some JS code which I want to convert to PHP code. I changed all the things that I know should, but it doesn't give the same result.

The PHP code I created from the JS code:

<?php
function hashCode($str){
    $hash = 0;

    if (strlen($str) == 0) return $hash;

    for ($i = 0; $i < strlen($str); $i++) {
          $char = $str[$i];
          $hash = (($hash<<5) - $hash) + $char;
          $hash = $hash & $hash;
    }
    return $hash;
}
?>

When entering a string it returns 0 and that is not because of the if function.
Original code:

hashCode = function(str){
    var hash = 0;
    if (str.length == 0) return hash;
    for (i = 0; i < str.length; i++) {
        char = str.charCodeAt(i);
        hash = ((hash<<5)-hash)+char;
        hash = hash & hash; // Convert to 32bit integer
    }
    return hash;
}

Can someone please help me?

Arend-Jan

1 Answer 1

2

This is because, in the javascript, the char is the code of the caracter (charCodeAt). So this will do the same. Use ord($char)

function hashCode($str) {
    $hash = 0;
    if (strlen($str) == 0) {
        return $hash;
    }
    for ($i = 0; $i < strlen($str); $i++) {
        $char = $str[$i];
        $hash = (($hash << 5) - $hash) + ord($char);
        $hash = $hash & $hash;
    }
    return $hash;
}

If string is ABCD, the output will be this, in both case:

65
2081
64578
2001986
2001986
Sign up to request clarification or add additional context in comments.

1 Comment

It doesn't work, I tried with an simple word like "felien" and there came JS:-1278196699 and PHP:3016770597 so it doesn't work completely.

Your Answer

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.