0

Say I've got one array like this

$users_names=array(1=>"Abby",2=>"Betty",3=>"Cathy",4=>"Debby");

And another like this

$users_admin=array(1,3);

What is the best way to implode the $users_admin array matching to $users_names?

For example, I would want to do something like this:

echo implode(", ",magical_array_function($users_admin,$users_names));

//echos: "Abby, Cathy"

What I've been doing is this...

foreach ($users_admin as $id_user) $toEcho.=$users_names[$id_user].", ";
echo substr($toEcho,0,-2);

But I know there must be a more efficient way to do it in one line

2
  • Look into array_keys() Commented Feb 10, 2014 at 19:40
  • I use array_keys() all the time. Just re-read the info on it. Still wouldn't know how to do what I'm trying to do. Want to try to submit an example? Commented Feb 10, 2014 at 19:43

1 Answer 1

3

You're looking for array_intersect_key here.

array_intersect_key($users_names, array_flip($users_admin))
Sign up to request clarification or add additional context in comments.

2 Comments

That does it! thanks Rocket! Will submit as answer when I'm able
@rgbflawed: Will submit as answer when I'm able - This made me think you were going to add an answer saying "Hey! It works, thnx for the solution!". Many people actually do that, so I was just making sure. Sorry!

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.