nsilva
nsilva

Reputation: 5614

PHP - Check if an array value is in another array

So I have two arrays:

$gated_categories
array(2) { [0]=> int(3511) [1]=> int(3510) }

and

$category_id
array(3) { [0]=> int(3518) [1]=> int(3511) [2]=> int(3502) }

As you can see above, both arrays contain 3511

So if $gated_categories contains a value which is is $category_id

I want this to return true, else false

I have tried with this:

$is_gated = !array_diff($gated_categories, $category_id);

But this is returning false, any ideas?

Upvotes: 1

Views: 667

Answers (3)

azibom
azibom

Reputation: 1934

You can solve this problem with use from array_diff two times

<?php
$gated_categories = [3511, 3510];
$category_id = [3518, 3511, 3502];

print_r(findGatedCategoriesContainCategoryId($gated_categories, $category_id));

function findGatedCategoriesContainCategoryId($gated_categories, $category_id) {
    $arrayDiff = array_diff($gated_categories, $category_id);
    return array_values(array_diff($gated_categories ,$arrayDiff));
}
?>

output

Array
(
    [0] => 3511
)

Or just use array_intersect like this

<?php
$gated_categories = [3511, 3510];
$category_id = [3518, 3511, 3502];

$result = array_intersect($gated_categories, $category_id);
print_r($result);
?>

output

Array
(
    [0] => 3511
)

Upvotes: 0

Mitya
Mitya

Reputation: 34556

array_diff() does the opposite of what you want. It returns an array with the values of the first array that are not present in the other array(s).

You need array_intersect().

if (count(array_intersect($arr1, $arr2))) {
    //at least one common value in both arrays
}

Upvotes: 3

M074554N
M074554N

Reputation: 71

You can do the following, loop over the array you want to check it's values and use in_array function.

Something like this:

<?php

    function checkCategory(): bool {
        $gated_categories = [3510, 3511];
        $category_id = [3502, 3511, 3518];
        
        foreach ($gated_categories as $cat) {
            if (in_array($cat, $category_id)) {
                return true;
            }
        }
        
        return false;
    }
    
    var_dump(checkCategory());

Upvotes: 0

Related Questions