phparraysmultidimensional-arrayfilterarray-intersect

Check if any rows of a 2d array share the same column value as a row in another 2d array


I want to compare two arrays if an email address in array 1 exists in array 2 (here: uname1@email.com). In that case it should display that the email already exists.

$Array1 = [
    [
        'username' => 'uname1',
        'name' => 'fullname1',
        'email' => 'uname1@email.com'
    ],
    [
        'username' => 'uname2',
        'name' => 'fullname2',
        'email' => 'uname2@email.com'
    ],
    [
        'username' => 'uname3',
        'name' => 'fullname3',
        'email' => 'uname3@email.com'
    ],
];

$Array2 = [
    [
        'username' => 'uname1',
        'name' => 'fullname1',
        'email' => 'uname1@email.com'
    ],
];

Solution

  • You might want to consider using the email as the key. Something like this:

    $a1 = array();
    foreach ($Array1 as $v) $a1[$v['email']] = $v;
    
    $a2 = array();
    foreach ($Array2 as $v) $a2[$v['email']] = $v;
    
    $intersection = array_values(array_intersect_key($a1, $a2));
    

    This yields an array that contains all the values of the first array that have an email present in the second array. You can then iterate through that array to display error messages.