0

I have a table that I am reading two columns from using PDO::FETCH_KEY_PAIR. I then need check if a value from another query exists in the array returned by the PDO fetch. To illustrate:

$id = array();
/* array returned by PDO::FETCH_KEY_PAIR query */
$mailTo = array (
    'MailTo1' => 6143,
    'MailTo2' => 6137,
    'MailTo3' => 6137,
);

echo $mailTo['MailTo1'];  //6143

$result1['needle'] = 'MailTo1';  //needle from second query to seek

if(in_array($result1['needle'], $mailTo)){
    $id['mailTo'] = $mailTo[$result1['needle']]; //null
}

using variable $result['needle'] returns null, but to verify that in_array returns the correct element I have used:


if(in_array('MailTo1', $mailTo)){
    $id['mailTo'] = $mailTo[$result['needle']];  //6143
}

Hard coding the needle returns the correct element. Taking the needle out an array and passing as a simple variable also returns null, i.e.

$result = 'MailTo1';

if(in_array($result1, $mailTo)){
    $id['mailTo'] = $mailTo[$result1]; //null
}

I cannot figure out why passing the needle as a key=>value variable ($result1['needle']) fails. It seems like this is very common practice...

2 Answers 2

2

In order to compare keys you need to use array key exists. in_array only looks at values and not the keys.

array_key_exists("MailTo1",$mailTo)

Another approach would be to get all keys in one array and then you can use in_array()

$mailToKeys = array_keys($mailTo);
in_array("MailTo1", $MailToKeys)
Sign up to request clarification or add additional context in comments.

Comments

0

DOH!!! Wrong approach.. array_key_exists is what I should have been using!!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.