Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have two arrays of the same length containing some values.

$a = array("a","b","x","x");
$b = array("f","g","g","h");

Now I want to get the values from $b at the index postions from where $a is x.

 $ids = array_keys($a, 'x');
 $res = ???($b,$ids);
 print_r($res);

So what function will give me an Array containing g and h. Or is there even a more elegent (e.g. not using array_keys()) to do this?

share|improve this question
 
faster way? your current code runs slow? –  Your Common Sense Jan 19 '13 at 12:06
 
Sorry. I ment it in the aspect of more elegant. –  jakob r Jan 19 '13 at 12:15
1  
array_intersect_key($b, preg_grep('/^x$/D', $a)) (Using regex is clearly, always, the more elegant solution. *grin*) –  salathe Jan 19 '13 at 12:48
add comment

1 Answer

$needle = 'x';
$res    = array();
foreach($a as $key => $value) {
    if ($value == $needle) {
        $res[] = $b[$key];
    }
}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.