i make cypher translator. I have an issue with translating encrypted characters ending with dots. I have following dictionary:
$dict = array(
"I"=>"1",
"L"=>"1.",
"O"=>"0",
"Q"=>"0.",
"Z"=>"2",
"?"=>"2."
);
When I use this:
function decode($cypher,$dict){
$sepp = explode(" ",$cypher);
foreach($sepp as $char){
echo array_search($char,$dict);
}}
decode("1. 0. 2.",$dict);
I am getting:
IOZ
Instead of expected:
LQ?
>Solution :
By default, array_search performs the same comparison as the == operator, which will attempt to "type juggle" certain values. For instance, '1' == 1, '1.' == 1, and '1.' == '1' are all true.
That means that '1' and '1.' will always match the same element in your lookup table.
Luckily, the function takes a third argument, which the manual describes as:
If the third parameter
strictis set totruethen thearray_search()function will search for identical elements in thehaystack. This means it will also perform a strict type comparison of theneedlein thehaystack, and objects must be the same instance.
This makes it equivalent to the === operator instead. Note that '1' === 1, '1.' === 1, and '1.' === '1' are all false.
So you just need to add that argument:
echo array_search($char,$dict,true);