neverlastn
neverlastn

Reputation: 2204

php use array as index to array

If I have an array $dictionary and an array $words how can I use an array ($words) to index another array ($dictionary)?

The easiest I can think is:

function dict_dispatch($word,$dictionary) {
    return $dictionary[$word];
}

$translated = array_map('dict_dispatch', $words, 
                          array_fill(0, count($words), $dictionary));

e.g.

For example:

$dictionary = array("john_the_king"=>"John-The-King", "nick_great"=>"Nick-Great-2001");
$words=array("john_the_king","nick_great");

$translated = <??>

assert($translated==array("John-The-King","Nick-Great-2001"));

Notice that $dictionary might be quite large and it would be very nice if this operation is as fast as possible (that's why I don't use foreach in first place)

Upvotes: 3

Views: 205

Answers (3)

neverlastn
neverlastn

Reputation: 2204

It looks like my original solution is more or less the most efficient.

Upvotes: 0

gen_Eric
gen_Eric

Reputation: 227270

I don't know how efficient this is, but it works.

$translated = array_values(array_intersect_key($dictionary, array_flip($words)));

Upvotes: 2

Xeoncross
Xeoncross

Reputation: 57194

Are you talking about something like this where you use array of the keys and another for the values?

$translated = array_combine($words, $dictionary);

Upvotes: 0

Related Questions