简体   繁体   中英

How to compare arrays with different sizes

I want to compare 2 arrays, except the two arrays may sometimes be of different sizes.

For example, I have a form and I receive the values with this:

// The post send more values than other array:
//   name , email , password, phone , address
// but in other cases send only one value and the other array it's bigger
foreach($_POST as $key=>$value)
{    
    $fields_array[]=$key;    
}

On the other side, I have this other array that I want to compare against:

    $fields_compare=array("name","email");

In this case when the array called $fields_array is the larger one, I don't have a problem. However, if for example the second array is larger, I have problems.

I continued and did this:

$aa=array_diff($fields_array,$fields_compare);
$bb=array_intersect($fields_array,$fields_compare);

foreach ($aa as $aaa)
{
    // Show the others different values, no show name and email
    print "".$aaa."<br>";
}

foreach ($bb as bbb)
{
    // Show the same Values in this case the same will be name and email ///
    print "".$bbb."<br>";
}

All this works if the first array is larger, but in other cases it doesn't work and doesn't show the real differences.

I'm not sure if this is what you're after, but what about just testing the input value types as you loop through the POST'd values?

$fields_compare=array("name" => true, "email" => true); //faster than in_array( );
foreach($_POST as $key=>$value)
{    
    if(isSet($fields_compare[$key]))
    {
        //do something (eg: save $value to text file)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM