I have a hash map which contains certain keys which are the sorted versions of their values. For example,
$hash = array( "abc" => "cab",
"aas" => "sas"
);
I also have an array of sorted strings($sorted_words) and I want to compare all these strings with the keys of the above hash map and if a match is found, store the corresponding value in a string. I use === and also strcmp(), but neither works. It always says the strings didn't match. Here is my code :
foreach($sorted_words as $sc) {
foreach($hash as $key => $value) {
if(strcmp($sc, $key) == 0) { // or if($sc === $key)
$string_match .= $value; // store the corresponding value for the matched key.
}
}
}
But the comparison fails as strcmp() always returns greater than 1 and '===' never returns true. Can anyone tell what's wrong ? I'm pretty sure there are strings that will match.
Try this :
$string_match = "";
foreach($sorted_words as $sc) {
if(array_key_exists($sc, $hash)){
$string_match .= $hash[$sc];
}
}
When a programmer stuck, they have to start debugging
foreach($sorted_words as $sc) {
foreach($hash as $key => $value) {
if($sc === $key) {
$string_match .= $value; key.
}
var_dump($sc, $key, $sc === $key);
}
}
and then study the output.
This is the only way to be sure, if there are any strings that match.
While your current "pretty sure" is a mere guess.