3

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)

6
  • 1
    Are you saying you want to construct an array from another array, using an array of indexes? Commented Sep 28, 2011 at 15:28
  • 2
    Could you give a small example of what data you would have and what you'd like to end up with? Commented Sep 28, 2011 at 15:31
  • Thanks a lot, I Just added an example Commented Sep 28, 2011 at 15:39
  • What's wrong with the code you have? Commented Sep 28, 2011 at 15:43
  • It's correct - but I'm wondering if there's something a bit more native/faster as in Ruby/Python... Commented Sep 28, 2011 at 15:46

3 Answers 3

2

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

$translated = array_values(array_intersect_key($dictionary, array_flip($words)));
Sign up to request clarification or add additional context in comments.

3 Comments

It's very good but a bit tricky because array_flip is naughty and will not work very well if we have e.g. $words=array("john_the_king","nick_great","john_the_king"); It seems quite efficient as far as I can tell.
Actually, a quick test using microtime() shows it to be a bit slower than the OP's code.
@neverlastn: I didn't think of that, yeah that would be a problem.
0

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

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

1 Comment

Thanks a lot! Not exactly. I added an example for clarity.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.