0

Ok it's late night and I'm working non-stop from too many hours so here's why I don't manage to understand what's the problem here. I have an array:

Array
(
    [bob] => 
    [mike-2] => 
    [tara] => example.com
)

I want to get the key searching for value so I'm using array_search:

// With an if statement...
if(in_array($_SERVER['SERVER_NAME'], $array)!==false)
{
    // something
}

// ... and also directly with this
$key = array_search($_SERVER['SERVER_NAME'], $array);
echo $key;

Result? Always false! There's no way for me to get tara when I'm looking for example.com. What the heck am I missing? I even tried replacing $_SERVER['SERVER_NAME'] directly with "example.com" but of course it still doesn't work.

Edit: it was a typo error... damn. I wasted 2 hours for this.

user1274113
  • 436
  • 8
  • 21
  • Is there something wrong with the array? can you print your array in PHP first? – Gary Liu Jun 12 '15 at 02:26
  • Sure. The array is totally fine. I can see all elements, keys and values. – user1274113 Jun 12 '15 at 02:39
  • This question might help. http://stackoverflow.com/questions/21809116/how-to-use-php-in-array-with-associative-array – Craig Harshbarger Jun 12 '15 at 02:55
  • `array_search()` is case-sensitive, could that be throwing you off? Are there trailing spaces in the values of `$array`? Does `array_search('example.com', $array)` work as expected? – mike.k Jun 12 '15 at 03:02
  • 1
    Oh my god. I've found the probem. I can't belive that I wasted 2 hours for a typo error. I was looking for a string "hcm" but it was "hmc". Damn! Thank you anyway for your help. – user1274113 Jun 12 '15 at 03:15

3 Answers3

5

Stop working. This is an actual answer. Just stop. Whenever it comes to you wasting two hours on a typo you're doing nobody any good, especially yourself.

Rest, you're not getting anywhere like this.

vcanales
  • 1,818
  • 16
  • 20
0

Try this instead

    $test= array('bob' => '','mike' => '','tara' => 'serverName');
while(list($key,$value) = each($test))
{
    if($value==$_SERVER['SERVER_NAME'])
    {
        echo $key;
        break;
    }
}
Dinuka Dayarathna
  • 169
  • 1
  • 3
  • 9
0

Array search is case sensitive, $_SERVER['SERVER_NAME'] will return the name in upper case so you have to convert it lower case in your case to work properly, additionally try to map the array also to lowercase Try the given example

$data = array

(
    'bob' =>'', 
    'mike-2' =>'', 
    'tara' =>'example.com'
);
array_search(strtolower($_SERVER['SERVER_NAME']), array_map('strtolower', $data));
Ankit Arjaria
  • 111
  • 1
  • 7