Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two way mapping class for static strings in php

Tags:

php

What could be the best way to implement 2 way mapping class for static strings in php. I thought having Enum class having 6 constants for 2 way mapping of 3 key value pair. Please suggest better implementation.

Eg:if I have a following mapping, I need to get Mangalore if I refer M and I also need to get M if I refer Mangalore

M=> Mangalore
D=> Delhi
O=> Ooty

Thanks !!

like image 676
Ruhi Singh Avatar asked Feb 26 '26 23:02

Ruhi Singh


1 Answers

I thought having Enum class having 6 constants for 2 way mapping of 3 key value pair. Please suggest better implementation.

Don't need a special class for this unless you absolutely need to. Simple PHP Arrays can do this

<?php

$names=array();
$names["M"]="Mangalore";
$names["D"]="Delhi";
$names["O"]="Ooty";

echo $names["M"]; //  Mangalore
echo array_search("Mangalore", $names); //M
?>

Edit

You could also write a small function for this

<?php

$names=array();
$names["M"]="Mangalore";
$names["D"]="Delhi";
$names["O"]="Ooty";

echo getMapping($names,"M");
echo getMapping($names,"Mangalore");

function getMapping($values,$search)
{
    if(array_key_exists($search,$values))
    {
        return $values[$search];
    }
    $key=array_search($search,$values);
    if($key)
    {
        return $key;
    }
    return 0;
}


?>
like image 129
Hanky Panky Avatar answered Feb 28 '26 12:02

Hanky Panky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!