Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 649
daGrevis Avatar asked Aug 30 '11 09:08

daGrevis


1 Answers

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)

like image 127
Paul Avatar answered Dec 03 '22 03:12

Paul