Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3

Thread: array problem

  1. #1
    New Coder
    Join Date
    Nov 2004
    Posts
    78
    Thanks
    0
    Thanked 0 Times in 0 Posts

    array problem

    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

    PHP Code:
    <?
    $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
    Last edited by graziano; 02-26-2007 at 09:09 AM.

  • #2
    Senior Coder
    Join Date
    Feb 2003
    Posts
    1,665
    Thanks
    0
    Thanked 27 Times in 25 Posts
    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…
    PHP Code:
    $ips = array(
        
    'server1' => '12.12.12.12',
        
    'server2' => '12.12.12.13',
        
    'server3' => '12.12.12.14'
    ); 
    i.e.
    PHP Code:
    $arrayname = array(
        
    'indexkey1' => 'value1',
        
    'indexkey2' => 'value2',
        
    'indexkey3' => 'value3'
    ); 

  • #3
    Regular Coder
    Join Date
    Oct 2006
    Location
    Bristol
    Posts
    128
    Thanks
    0
    Thanked 0 Times in 0 Posts
    I think you could also use array_key_exists().

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

    Alex
    Give me Rep if I was helpful and ignore if I wasn't ;)

    http://www.google.com <--use this before asking

    Nominate a Helpful Member



  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •