...

View Full Version : array problem



graziano
02-26-2007, 10:07 AM
Hello

I have an array with of server ip with server name like this

$ips = array(
"12.12.12.12" => "server1",
"12.12.12.13" => "server2",
"12.12.12.14"=> "server3"
);


I am trying to write the code to check if a $newip exists on the $ips array
and if exists I wish to show the server name for that ip.
How to do that please ?

For example if $newip = 12.12.12.13 since it exists on $ips , the code should return "server2".

I am trying



<?
$ips = array(
"12.12.12.12" => "server1",
"12.12.12.13" => "server2",
"12.12.12.14"=> "server3"
);


$newip="12.12.12.13";
if (in_array($newip, $ips ))
{
echo "exists $ips[$newip]";
}
else
{
echo "not exists";
}

?>



but it does not work , I always receive "not exists";

Any help please ?
Thanks

Bill Posters
02-26-2007, 10:20 AM
You're checking to see if an array 'key' is present in the array, when you should presumably be checking for values.

Given the way you've constructed your array, the values are 'server1', 'server2' and 'server3', so checking for '12.12.12.13' will return 'not exists'.

Try…

$ips = array(
'server1' => '12.12.12.12',
'server2' => '12.12.12.13',
'server3' => '12.12.12.14'
);

i.e.

$arrayname = array(
'indexkey1' => 'value1',
'indexkey2' => 'value2',
'indexkey3' => 'value3'
);

Alex!
02-26-2007, 12:18 PM
I think you could also use array_key_exists().

http://uk.php.net/manual/en/function.array-key-exists.php

Alex



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum