More flexibility in searching an array

Discussion in 'PHP' started by jayg5000, Feb 29, 2008.

  1. #1
    I am trying to search an array to see if it contains a certain word but the in_array(); function (form what I can see) needs to be the exact value of the array values. Here is an example:

    $fruit = array('Green Apple', 'Yellow Banana', 'Red Cherry');
    Code (markup):
    How would I search $fruit to see if it contains the word "Green" or "Cherry?" Maybe I'm thinking so hard I can't see the simple solution. Thanks for any help.
     
    jayg5000, Feb 29, 2008 IP
  2. RoscoeT

    RoscoeT Peon

    Messages:
    78
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #2
    You could use foreach and loop through the array preforming a strpos on each element.

    Try something like this untested copied and pasted junk...

    
    $fruit = array('Green Apple', 'Yellow Banana', 'Red Cherry');
    
    foreach ($fruit as $mystring){
       $findme   = 'Green';
       $pos = strpos($mystring, $findme);
    
       // Note our use of ===.  Simply == would not work as expected
       // because the position of 'a' was the 0th (first) character.
       if ($pos === false) {
           echo "The string '$findme' was not found in the string '$mystring'";
         } else {
           echo "The string '$findme' was found in the string '$mystring'";
           echo " and exists at position $pos";
       }
    }
    
    
    PHP:
     
    RoscoeT, Feb 29, 2008 IP