Home > front end >  Array as variable for in_array
Array as variable for in_array

Time:10-04

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...

CodePudding user response:

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)

CodePudding user response:

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

  • Related