tags:

views:

39

answers:

4

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

$Array1 = Array
(        
[0] => Array
        (
            [username] => uname1
            [name] => fullname1
            [email] => [email protected]

        )
[1] => Array
        (
            [username] => uname2
            [name] => fullname2
            [email] => [email protected]    
        )
[2] => Array
        (
            [username] => uname3
            [name] => fullname3
            [email] => uname3@@email.com    
        )        
}   

$Array2 = Array
(    
[0] => Array
        (
            [username] => uname1
            [name] => fullname1
            [email] => [email protected]    
        )
}
A: 

Pretty standard.

<?php
function userExists() {
    global $Array1, $Array2;
    for($Array2 as $user) {
        for($Array1 as $existingUser) {
            if($user['email'] == $existingUser['email']) {
                return true;
            }
        }
    }
    return false;
}
if(userExists())
    echo 'user exists.';
?>
Matt Williamson
Consider that this algorithm is O(n^2).
Gumbo
A: 

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.

Victor Nicollet
+1  A: 

I would build an index of array 2 where the email address is the key:

$index = array();
foreach ($Array2 as $item) {
    $index[$item['email']] = true;
}

Then checking for an existing email address costs only O(1) for every item in array 1:

foreach ($Array1 as $item) {
    if (isset($index[$item['email']])) {
        echo 'email already exists';
    }
}
Gumbo
A: 

Its easy.

$result = array_search($Array2[0], $Array1)
var_dump($result);

If you want to check whether something was found, remember to do it like this:

 if ($result !== false) { print "Found!"; }

The reason is that array_search can return integer 0, if result was found at index 0 in $Array1 and writing the check as

 if ($result == false) { print "Not found"; }

will print "Not found" in this case.

Anti Veeranna
I'm not sure if it works with arrays and even if it does, it would only work if `username` and `name` are also the same.
Felix Kling
It does work with arrays, I tried before posting. And yes, it has to be exact match, both username and name have to match as well.
Anti Veeranna