madcrazydrumma madcrazydrumma - 7 months ago 34
PHP Question

Excluding all elements but one

I have an array of things:

$arr = array('Apple', 'Pear', 'Pineapple');

I want to exclude everything apart from, say, 'Apple' in the array. I had a look at using array_diff, however I don't know how I would apply using that in my situation.

array_diff($arr, array('Apple'));
obviously excludes 'Apple' from the list.

Thanks for the help!

EDIT: Since more details are required, I have to process data from an API I'm using which takes an exclusion list to simplify the JSON response. Therefore I'm using the array containing possible options to exclude.


Assuming you are iterating through the array and not just simply removing 'Apple' values from the array... you can add a condition check inside a loop which checks for any value.

foreach($arr as $key => $value){
    if($value != 'Apple'){ //array value is not 'Apple,' do something
        //do something