1

I have two arrays:

$arr_a = ['A', 'F', 'C', 'D', 'E', 'B'];
$arr_b = ['D', 'A', 'F'];

, and I need an array with values of $arr_b that is sorted by $arr_a, like this:

array(3) {[0]=>string(1) "A", [1]=>string(1) "F", [2]=>string(1) "D"}

What would be the best way to do it?

PS. All the entries in $arr_b are present in $arr_a, and there is no double entries in $arr_b, and the keys in resultin array are irrelevant, really.

4
  • Have you tried any ways so far? You can iterate over $arr_a, checking against $arr_b, and creating a newly formatted $arr_c- but I'm sure theres a better way to do this with a sort function, so I'll leave this in the comments. Commented Dec 3, 2015 at 16:15
  • What if $arr_b contains more items or items that are not in $arr_a? Commented Dec 3, 2015 at 16:16
  • Will there ever be values in b, that are not in a? Commented Dec 3, 2015 at 16:16
  • All the values of $arr_b are always in $arr_a, no need to take that in account. Also the keys in resulting array are irrelevant, really. And $arr_b is done with array_unique, so no double entries. I've tried iterating the array, making new one and then multisorting, but there must be a reasonable way, too? :) Commented Dec 3, 2015 at 16:18

2 Answers 2

3

Probably not a job for sorting. array_intersect() will return items in $arr_a that are in $arr_b in the order that they are in $arr_a:

$arr_b = array_intersect($arr_a, $arr_b);

If you need to re-index then just use array_values() afterward.

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

2 Comments

Damn. Blew my answer out of the water :D +1
Damn me too :) Simple and whatnot else. No reason not to accept it as an answer. Cheers!
2

This is what I think you want but your question is not too clear.

$result = array_filter($arr_a, function($item) use($arr_b){
    return in_array($item, $arr_b);
});

Which results in

array(3) {
    [0] = string(1) "A"
    [1] = string(1) "F"
    [3] = string(1) "D"
}

1 Comment

does the job exactly how it should, thank you very much. Still Abracadever's seems shorter and a little cleverer.

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.