SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Evangelist
    Join Date
    Feb 2000
    Location
    England
    Posts
    568
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Getting key from array when value is known.

    This seems like it should be easy but i can't do it.

    Say i had:

    $array = array('10' => 'Yes', '20' => 'No');

    I have the value "No" and i want to get the number 20 from the array.

    Don't worry about duplicates, if there are any they will always have the same id.

    Anybody know how to do this. I tried php.net and there was a function someone had submitted to use this but I have found it unreliable. Works sometimes but not others and I don't know why.

    I include it here:

    PHP Code:
        function array_binary_search($needle$haystack) {
    $l=0;
    $u=count($haystack);
    $m=($l+$u)/2;
    $j=0;
    $k=1;

    while(
    $l <= $u) {
        
    $j++;
        
    $k++;
        if ( 
    $needle $haystack[$m] )
        
    $l floor($m 1);
        if ( 
    $needle <= $haystack[$m] )
        
    $u $m 1;
        
    $m = ($l+$u)/2;
    }

    if (
    $haystack[$l] != $t)
    return -
    1;
    return 
    $l;


  2. #2
    SitePoint Addict zoordaan's Avatar
    Join Date
    Feb 2001
    Location
    NYC/Texas
    Posts
    348
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The array_keys function should work for this.

    http://www.php.net/manual/en/function.array-keys.php

  3. #3
    SitePoint Evangelist
    Join Date
    Feb 2000
    Location
    England
    Posts
    568
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    doh. i was trying to use array_search

    http://www.php.net/manual/en/function.array-search.php

    thanks


Bookmarks

Posting Permissions

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