Page 1 of 1

Problems with using in_array

Posted: Thu Jan 07, 2010 10:42 am
by atyler
I'm confused as to why the following code returns the results that it does. Are there some nuances of the in_array function that prevent this from working as expected?

Thanks for any input.

Code: Select all

<?php
$dnsIp = dns_get_record("example.com", DNS_A);
print_r($dnsIp);
 
if (in_array("1.2.3.4", $dnsIp, false)){
echo "Found.";
} else {
echo "Not found.";
}
?>
The result of running this is:
Array ( [0] => Array ( [host] => example.com [type] => A [ip] => 1.2.3.4 [class] => IN [ttl] => 32533 ) )

Not found.

Re: Problems with using in_array

Posted: Thu Jan 07, 2010 10:52 am
by AbraCadaver
Number one, example.com resolves to 192.0.32.10 not 1.2.3.4 :-)

Secondly, dns_get_record() is returning a multi-dimensional array, so this is what it needs to be (in array only looks in the array, not deeper dimensions of that array):

Code: Select all

if (in_array("192.0.32.10", $dnsIp[0], false)){

Re: Problems with using in_array

Posted: Thu Jan 07, 2010 11:02 am
by atyler
Oh sure...that makes perfect sense; not sure how I overlooked that (the mulitdimensional array, not the IP - 1.2.3.4 isn't what I'm actually testing against, nor is example.com really what I'm using, as I'm sure you know). :D

Thanks for the help!

Re: Problems with using in_array

Posted: Thu Jan 07, 2010 11:08 am
by AbraCadaver
atyler wrote:Oh sure...that makes perfect sense; not sure how I overlooked that (the mulitdimensional array, not the IP - 1.2.3.4 isn't what I'm actually testing against, nor is example.com really what I'm using, as I'm sure you know). :D

Thanks for the help!
Yes I knew that, hence the smilie :-)

If all you're ever going to do is get an A record, then gethostbyname() might be more portable.

Re: Problems with using in_array

Posted: Thu Jan 07, 2010 11:30 am
by atyler
Cool. Good suggestion.

Thanks!