Re: array search

From: Date: Sun, 23 Jan 2005 19:00:44 +0000
Subject: Re: array search
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-207092@lists.php.net to get a copy of this message
Ah so -- array_search only works on values ? That probably accounts for my first day or so, thanks. I've got it now. On Sun, 23 Jan 2005 19:22:32 +0100, M. Sokolewicz <tularis@php.net> wrote:
Malcolm wrote:
Hello All, I've been trying for days now to make this work. I'm trying to search my array for a value and return the key. I get the visitor's IP and try this -- this is the latest, I've tried a few functions to echo the name associated with the viz_ip. $viz_ip= $_SERVER['REMOTE_ADDR']; $byte_ip= array( "204.126.202.56"=>"Mark", "63.230.76.166"=>"Bob", "63.220.76.165"=>"John", ); function _array_search ($viz_ip, $byte_ip) {
    foreach($byte_ip as $key => $val) {
        if ($viz_ip === $key) {
           return($val);
       }
    }
    return(False);
} I'm no wiz but this shouldn't be this hard, maybe I'm thinking wrong. I've read the examples at php.net but I just can't get it. Some help or even a hint ? best regards, malcolm
I might be the only one to notice here, but you don't want to find the KEY, you want to find the VALUE. Otherwise, you'll need to assemble your array differently. $viz_ip= $_SERVER['REMOTE_ADDR']; $byte_ip= array(
    "204.126.202.56"=>"Mark",
    "63.230.76.166"=>"Bob",
    "63.220.76.165"=>"John"
); That means: $byte_ip[$viz_ip] = some_name; That's because you have ips set as your *keys*, and not your values. To do what you wanted, simply either: a) reverse the array, making keys values and values keys: $byte_ip= array(
    "Mark"=>"204.126.202.56",
    "Bob"=>"63.230.76.166",
    "John"=>"63.220.76.165"
); or: b) change the function to match on key (for which you don't *need* a function). - Tul
-- Ommmm

« previous php.general (#207092) next »