1

I am trying to detect if a smaller Array is is in a larger array.

Legend:

$user = Larger Array 
$TMP = Smaller Array

Example:

$TMP  =  
Array
(
    [user] => Array
    (
        [timezone] => -8
    )

)

$user =

Array
(
    [_id] => MongoId Object
        (
            [$id] => example
        )

    [userid] => 275
    [user] => Array
    (
        [email] => [email protected]
        [id] => 48339
        [timezone] => Array
            (
            )

    )
)

In this case I would want a script that would return false.

But if timezone -8 was already in user I would want it to be true

I tried already:

$isSubset = 0 == count(array_diff($TMP, $user));
3
  • if ($TMP['user']['timezone']==$user['user']['timezone']){ ..} ?? Commented Sep 10, 2014 at 1:24
  • This will not work, as $TMP and $user are automatically generated and can change the value I am looking to identify. Commented Sep 10, 2014 at 1:26
  • Why not just compare what you want to compare? array_diff($TMP['user']['timezone'], $user['timezone']); Commented Sep 10, 2014 at 1:26

2 Answers 2

1

A recursive function that checks that every key and leaf values in the smaller array exist in the larger array

function is_subset($smaller,$larger) {
    foreach($smaller as $k => $v) {
        if(!array_key_exists($k,$larger))
            return false;

        if(!is_array($v)) {
            if($v == $larger[$k])
                continue;
            else return false;            
        }
        else if(!is_subset($v,$larger[$k]))
            return false;
    }  
    return true;
}

$smaller = array('user' => array('timezone' => 2));
$larger = array('one' => 1,'user' => array('timezone' => 1));
var_dump(is_subset($smaller,$larger)); // false

$smaller = array('user' => array('timezone' => 1));
$larger = array('one' => 1,'user' => array('timezone' => 1));
var_dump(is_subset($smaller,$larger)); // true
Sign up to request clarification or add additional context in comments.

Comments

1

You can directly compare from base array for effenciency

 function checksub($arr,$subarr){
    foreach($arr as $key=>$value){
        if($value==$subarr)
           return true;
        else{
            if(is_array($value)){
                return checksub($value,$subarr);
            }
        }
    }
    return false;
}
$array=array("a"=>1,"b"=>2,array("x"=>array("some","data","z"=>"w")));
$sub=array("x"=>array("some","data","z"=>"w"));
$nosub=array("x"=>array("some","data","z"=>"changed"));
$sub2=array("some","data","z"=>"w");
var_dump(checksub($array,$sub));
var_dump(checksub($array,$sub2));
var_dump(checksub($array,$nosub));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.