Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

array_search() not matching numbers with dots

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 strict is set to true then the array_search() function will search for identical elements in the haystack. This means it will also perform a strict type comparison of the needle in the haystack, 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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading