1

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?

2
  • Use a nested for loop. Iterate through them and check when is $i the same Commented Jan 19, 2021 at 10:50
  • 1
    array_diff returns the difference between two arrays, but you are negating the obtained result, that's why you are obtaining a boolean value. Use array_intersect instead. Commented Jan 19, 2021 at 10:53

3 Answers 3

3

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

Works perfectly, just missing a close bracket I think. if (count(array_intersect($arr1, $arr2))) { #do stuff }
Apologies, typo. Edited.
0

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());

Comments

0

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
)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.