Home > Net >  array_search() not matching numbers with dots
array_search() not matching numbers with dots

Time:12-15

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?

CodePudding user response:

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);

CodePudding user response:

You just need to do a strict search.

See 3rd parameter of array_search.

function decode($cypher,$dict){

    $sepp = explode(" ",$cypher);

    foreach($sepp as $char){
      echo array_search($char,$dict,true);
    }
}

The reason it doesn't work without is because php thinks 1 and 1. is the same number.

CodePudding user response:

This line would help you. Set third parameter to true. This causes the comparison to run in strict mode.

echo array_search($char, $dict, true);

function decode($cypher, $dict)
{
    $sepp = explode(" ",$cypher);
    foreach ($sepp as $char) {
        echo array_search($char, $dict, true);
   }
}

CodePudding user response:

If you have a one-one map, you can just flip your map, and use the array to translate your cipher directly.

<?php
$dict = array(
     'I'=>'1',
     'L'=>'1.',
     'O'=>'0',
     'Q'=>'0.',
     'Z'=>'2',
     '?'=>'2.'
);

$cipher = "1. 0. 2.";

$decode = strtr($cipher, array_flip($dict));

var_dump($decode);

Output:

string(5) "L Q ?"
  •  Tags:  
  • php
  • Related