Hi

I'm having a problem with array_search, i can get it working from a hard coded array, but when the array has been created from a string using explode("\n", $string); it doesn't work. It will return the last item key in the array if I search for that, but otherwise it returns nothing.

anyone know what's wrong? or a workaround?

thanks
nic

    Well, i now think it is'nt a problem with the explode as this works fine:

    $string = "a\nbig\nlong\nsentence";
    $search_for = "long";
    
    $array = explode("\n", $string);
    $found_key = array_search($search_for, $array);
    
    print $found_key;
    

    but i am bringing in the string from an external file like this.. (and it will only find the last word)

    $filename = "external.txt"; 
    $fp = fopen($filename, "rb");
    $string = fread ($fp, filesize($filename));
    fclose ($fp);
    
    $search_for = "long";
    
    $array = explode("\n", $string);
    $found_key = array_search($search_for, $array);
    
    print $found_key;
    

    the external.txt file looks like this...

    a
    big
    long
    sentence

      i think i see the problem. the array you are creating still has the new lines attached at the ends of each value. the array_search() function searches for an extact match on 'long', not 'long' with a new line at the end. try this code (btw, you don't need the fopen + explode stuff, php's file function does the same thing in one step):

      $array = file ('external.txt');
      foreach ($array as $key => $value) {$array[$key] = trim ($value);}
      $search_for = 'long';
      $found_key = array_search ($search_for, $array);
      echo '$found_key = ' . $found_key;
      

        Brilliant ! 🙂 😉

        that work great.
        Thanks for that, I've spent most of the day tring to work it out.

        thanks again
        nic

          Write a Reply...