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

冷暖自知 提交于 2019-12-10 14:48:51

问题


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!


回答1:


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)




回答2:


The array_diff function will work for you. http://php.net/manual/en/function.array-diff.php



来源:https://stackoverflow.com/questions/7241132/how-to-filter-array-values-from-another-arrays-values-and-return-new-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!