# How to map x=>y and y=>x?

#### Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

•  Subject
• Author
• Posted on

An associative array will only map x=>y how do you do map x=>y and
y=>x?

Appears that I have to do eg

\$arr = array (
"x" => "y",
"y" => "x",
)'

so
\$arr["x"] will give "y" and
\$arr["Y"] will give "x"

but I've 100 or so entries and that means to map both ways I need to
double the array size. There must be a better way.

## Re: How to map x=>y and y=>x?

There probably is. Perhaps if you described the problem you're trying to
solve, instead of the trouble you're having with one particular attempted
solution, someone could suggest what that better way might be.

## Re: How to map x=>y and y=>x?

drjn wrote:

You should use single-quoted strings where you do not need variable
expansion or special escape sequences like "\n"; they are more efficient
there because those substrings do not need to be scanned for.

\$map = array_merge(\$arr, array_flip(\$arr));

That assumes, of course, that no value occurs twice, otherwise there will
be partial data loss.  However, it may not be necessary to do that in the
first place.

RTFM:

<http://php.net/manual/en/function.array-flip.php
<http://php.net/manual/en/function.array-merge.php
<http://php.net/manual/en/function.array-search.php

PointedEars

## Re: How to map x=>y and y=>x?

Absolutely brilliant Thomas works a treat. I knew there must be a way
but had not thought of manipulating the array I thought there was
probable some mapping data structure out there that I could not find.

## Re: How to map x=>y and y=>x?

El 03/03/2010 20:53, drjn escribió/wrote:

Well, if you need that info, you have to use system resources: either
memory or CPU.

What are your exact needs and concerns?

--
-- http://alvaro.es - Álvaro G. Vicario - Burgos, Spain
-- Mi sitio sobre programación web: http://borrame.com
-- Mi web de humor satinado: http://www.demogracia.com
--