1

This is my array:

$keyArr = array(12345 => array("somto@gmail.com", "james@yahoo.com",), 54321 => array("munz@gmail.com",));

Here's my statement:

foreach ($keyArr as $dbkey => $dbvalue){
  if (!in_array($email, $dbvalue) && $dbkey != $key || in_array($email, $dbvalue) && $dbkey != $key || !in_array($email, $dbvalue) && $dbkey == $key){
    $errors['key'] = "Invalid email or key!";
  }
}

Say I create a variable that exists in $keyArr such as:

$key = 12345;
$email = "somto@gmail.com";

I expect no output from the program, because the values of $key and $email exist in $keyArr, but I still get the "Invalid email or key!" message.

1
  • It's not clear what you're trying to accomplish. Do you simply want to determine if the value in $email exists in the list referenced by $key? Jan 23, 2021 at 21:31

2 Answers 2

1

Since you got an associative array, you can actually do this without a loop:

if (!array_key_exists($key, $keyArr) || !in_array($email, $keyArr[$key])) {
    $errors['key'] = "Invalid email or key!";
}

Working example.

1
  • Perfect! I'll also try to get around using a loop, to aid my learning process. Thanks. Jan 23, 2021 at 22:15
1

Those values do not match every record so it will always display that error. You need to only set that error after you have looped through every item in the array and haven't found a match.

$error = true;
foreach ($keyArr as $dbkey => $emailAddresses){
  if ($dbkey === $key && in_array($email, $emailAddresses)) {
    // MATCH! Break out of the loop before we can set the error message
    $error = false;    
    break; 
  }
}
if ($error) {
    $errors['key'] = "Invalid email or key!";
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.