0

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?

3
  • faster way? your current code runs slow? Commented Jan 19, 2013 at 12:06
  • 1
    Sorry. I ment it in the aspect of more elegant. Commented Jan 19, 2013 at 12:15
  • 3
    array_intersect_key($b, preg_grep('/^x$/D', $a)) (Using regex is clearly, always, the more elegant solution. *grin*) Commented Jan 19, 2013 at 12:48

1 Answer 1

1
$needle = 'x';
$res    = array();
foreach($a as $key => $value) {
    if ($value == $needle) {
        $res[] = $b[$key];
    }
}
Sign up to request clarification or add additional context in comments.

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.