How to filter array values from another arrays values and return new array?

daGrevis picture daGrevis · Aug 30, 2011 · Viewed 8.3k times · Source

I have two arrays: $all_languages and $taken_languages. One contains all languages (like 200 or something), but second - languages that have been chosen before (from 0 to 200).

I need to remove all languages that have been taken ($taken_languages) from $all_languages and return new array - $available_languages.

My solution was two loops, but, first, it doesn't work as expected, second - it's 'not cool' and I believe that there are better solutions! Can you point me to the correct path?

This is what I have done before, but, as I said, it doesn't work as expected...

if (!empty($taken_languages)) {

    foreach ($all_languages as $language) {

        foreach ($taken_languages as $taken_language) {

            if ($taken_language != $language) {

                $available_languages[] = $language;

                break;

            }

        }

    }

} else {

    $available_languages = $all_languages;

}

Thanks in advice!

Answer

Paul picture Paul · Aug 30, 2011

PHP has a built in function for this (and just about everything else :P)

$available_languages = array_diff($all_languages, $taken_languages);

PHP Manual (array_diff)