Problems with using in_array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
atyler
Forum Newbie
Posts: 17
Joined: Tue May 26, 2009 10:28 pm

Problems with using in_array

Post 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.
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: Problems with using in_array

Post 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)){
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
atyler
Forum Newbie
Posts: 17
Joined: Tue May 26, 2009 10:28 pm

Re: Problems with using in_array

Post 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!
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: Problems with using in_array

Post 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.
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
atyler
Forum Newbie
Posts: 17
Joined: Tue May 26, 2009 10:28 pm

Re: Problems with using in_array

Post by atyler »

Cool. Good suggestion.

Thanks!
Post Reply