Checking If 2 Arrays Have at Least 1 Equal Value

Checking if 2 arrays have at least 1 equal value

array_intersect()

returns an array containing all the values of array1 that are present in all the arguments. Note that keys are preserved

$a = array(1, 2, 3, 4);
$b = array(4, 5, 6, 7);
$c = array_intersect($a, $b);
if (count($c) > 0) {
var_dump($c);
//there is at least one equal value
}

you get

array(1) {
[3]=>
int(4)
}

Checking if 2 arrays have at least 1 equal value

array_intersect()

returns an array containing all the values of array1 that are present in all the arguments. Note that keys are preserved

$a = array(1, 2, 3, 4);
$b = array(4, 5, 6, 7);
$c = array_intersect($a, $b);
if (count($c) > 0) {
var_dump($c);
//there is at least one equal value
}

you get

array(1) {
[3]=>
int(4)
}

How to know if two arrays have the same values

Sort the arrays and compare their values one by one.

function arrayCompare(_arr1, _arr2) {
if (
!Array.isArray(_arr1)
|| !Array.isArray(_arr2)
|| _arr1.length !== _arr2.length
) {
return false;
}

// .concat() to not mutate arguments
const arr1 = _arr1.concat().sort();
const arr2 = _arr2.concat().sort();

for (let i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i]) {
return false;
}
}

return true;
}

PHP - Check if two arrays are equal

$arraysAreEqual = ($a == $b); // TRUE if $a and $b have the same key/value pairs.
$arraysAreEqual = ($a === $b); // TRUE if $a and $b have the same key/value pairs in the same order and of the same types.

See Array Operators.

EDIT

The inequality operator is != while the non-identity operator is !== to match the equality
operator == and the identity operator ===.

JQuery check if two arrays have at least one common element

One way to do this is to loop through one array and use $.inArray for the second array..

function hasCommonElement(arr1,arr2)
{
var bExists = false;
$.each(arr2, function(index, value){

if($.inArray(value,arr1)!=-1){
console.log(value);
bExists = true;
}

if(bExists){
return false; //break
}
});
return bExists;
}

jSfiddle

and now we can check

if(hasCommonElement(arr1,arr2)){
return true;
}

Hopefully there would be a better answer...

Check if 2 arrays have at least one element in common?

Assuming the input arrays to be A and B, you can use np.in1d with np.any, like so -

import numpy as np
np.in1d(A,B).any()

You can also use NumPy's broadcasting capability, like so -

(A.ravel()[:,None] == B.ravel()).any()

How to know if two arrays have at least one equal element (f#)

It could be simpler:

let exists a b = (Set.ofArray a, Set.ofArray b) ||> Set.intersect |> (<>) Set.empty


Related Topics



Leave a reply



Submit