Reputation: 127
I have 2 arrrays, And i need return TRUE or FALSE when 2 arrays matched each other. also un-ordered arrays should return TRUE if results matched, but only should return true if both arrays have same values.
//This should return TRUE
$array_One = array('test1', 'test2', 'test3');
$array_Two = array('test1', 'test2', 'test3');
//This should return TRUE
$array_One = array('test1', 'test2', 'test3');
$array_Two = array('test1', 'test3', 'test2');
//This should return TRUE
$array_One = array('test1', 'test2', 'test3');
$array_Two = array('test1', 'test3', 'test2');
//This should return FALSE
$array_One = array('test1', 'test2', 'test3');
$array_Two = array('test1', 'test2');
I tried few methods, including array_key_exists by using foreach, But it does not returned the expected result. This should return ONLY one TRUE or FALSE when arrays matched.
Upvotes: 1
Views: 335
Reputation: 1221
this should work for you:
sort($array1);
reset($array1);
sort($array2);
reset($array2);
$res = array_diff($array1, $array2);
if($res)
echo "they match";
Upvotes: -1
Reputation: 6780
function arraycomp( $array1, $array2 ) {
$diff1 = array_values( $array1 );
$diff2 = array_values( $array2 );
sort( $diff1 );
sort( $diff2 );
return ( $diff1 === $diff2 );
}
Simply pass in your two arrays to that function.
Upvotes: 1
Reputation: 2272
If you want to compare the sizes of the arrays, what you can do is use count
:
if ( count ( $array1 ) == count ( $array2 ))
{
MATCH!
}
else
{
NO MATCH!
}
Upvotes: 1
Reputation: 10469
$array_One = array('test1', 'test2', 'test3');
$array_Two = array('test1', 'test3', 'test2');
if (array_diff($array_One, $array_Two))
{
// there is a difference
echo 'FALSE';
}
else
{
// the arrays match
echo 'TRUE';
}
Upvotes: 1
Reputation: 125604
http://php.net/manual/en/function.array-diff.php
If you just need to know if two arrays' values are exactly the same (regardless of keys and order), then instead of using array_diff, this is a simple method:
<?php
function identical_values( $arrayA , $arrayB ) {
sort( $arrayA );
sort( $arrayB );
return $arrayA == $arrayB;
}
// Examples:
$array1 = array( "red" , "green" , "blue" );
$array2 = array( "green" , "red" , "blue" );
$array3 = array( "red" , "green" , "blue" , "yellow" );
$array4 = array( "red" , "yellow" , "blue" );
$array5 = array( "x" => "red" , "y" => "green" , "z" => "blue" );
identical_values( $array1 , $array2 ); // true
identical_values( $array1 , $array3 ); // false
identical_values( $array1 , $array4 ); // false
identical_values( $array1 , $array5 ); // true
?>
Upvotes: 3