I have this code
$num = 0;
$arr = array();
for ($i = 1; $i <= 10000; $i ) {
$hashed = hash("joaat", "TEST" . $num $i);
if (!in_array($hashed, $arr)) {
array_push($arr, $hashed);
} else {
// array_push($arr, $hashed);
echo "Duplicate " . $hashed . "\n";
echo "<br>";
echo "TEST" . $num $i;
echo "<br>";
break;
}
}
echo "ARRAY---------------------------------------------------------------------------------------------------------------------------------";
echo "<br>";
print_r($arr);
As you can see, I create a string such as "Test1", "TEST2", "TEST3"... "TEST10000", and hash it with joaat algorithm. Then I check if the hashed value exist in array $arr. If the value doesn't exist, I add it to the array $arr. If it exist, I print the duplicate hash and the original string and stop the for loop.
The problem is, the program stops because it reaches the else condition and shows the duplicate hash and the original string
But when I search the value in the array, I found no duplicate
Can anybody explains to me why this happen? Maybe there is flaw in my code?
CodePudding user response:
This has to do with the fact that your number starts with 0e
. PHP will try to interpret it as a number in scientific notation. Since it starts with 0
, it will always be 0
no matter what's after the e
.
Try by adding something to the hash, like prepending it with the letter H
. You won't see the problem anymore.
Now, this happens because strings are converted to numbers behind the hood. Your real solution is to set the 3rd parameter of in_array to true. This will switch to strict search.