0

I have :

$a = array(
    0=>'you',
    1=>'will',
    2=>'be',
    3=>'so',
    4=>'happy',
    5=>'in'
);

$b = array(
    0=>'1',
    1=>'4',
    2=>'5'
);   // (KEYS:1,4,5)

I want out the values of $a that matches $b's keys;

so $val would be willhappyin.

And then comma-separate them.. like: will,happy,in without comma after last one.

How can i do this ? :)

1
  • What i have tried is somewhat like this, but i thought i had it all wrong.. and i was right :) Commented Feb 27, 2012 at 16:44

3 Answers 3

7
$string = implode(",", array_intersect_key($a, array_flip($b)));

EXPLANATION:

array_flip switches the values of $b to keys.

array_intersect_key takes only the entries in $a that are also present in $b.

implode joins the resulting array values together by comma.

Sign up to request clarification or add additional context in comments.

4 Comments

wow , first time hearing about this function array_intersect_keys - will use it in the future!
It's actually array_intersect_key.
@OfirBaruch: Actually, the function is array_intersect_key (no s on the end). See corrected answer.
Wow.. so easy :) here i have played with foreach for hours without getting my results. Thanks so much!!
2
$c = array();
foreach($b as $key)
{
  $c[] = $a[$key]
}

echo implode(",",$c);

Comments

0
$out_arr = array();
foreach ($b as $k => $v) {
  array_push($out_arr, $a[$v]);
}

return join($out_arr, ',');

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.