2

I am creating this array with the below code:

$ignored = array();
foreach(explode("\n", $_POST["ignored"]) as $ignored2) {
    $ignored[] = $ignored2;
}

and i want to check if any item inside the array is LIKE a variable. I have this so far:

if(in_array($data[6], $ignored)) {

but I'm not sure what to do with the LIKE

user3843997
  • 205
  • 1
  • 5
  • 9

3 Answers3

2

in_array() doesn't provide this type of comparison. You can make your own function as follows:

<?php
function similar_in_array( $sNeedle , $aHaystack )
{

    foreach ($aHaystack as $sKey)
    {
        if( stripos( strtolower($sKey) , strtolower($sNeedle) ) !== false )
        {
            return true;
        }
    }    
    return false;
}
?>

You can use this function as:

if(similar_in_array($data[6], $ignored)) {
    echo "Found";   // ^-search    ^--array of items
}else{              
    echo "Not found";
}

Function references:

  1. stripos()
  2. strtolower()
  3. in_array()
Ravi Dhoriya ツ
  • 4,435
  • 8
  • 37
  • 48
0

Well, like is actually from SQL world. You can use something like this:

  $ignored = array();
  foreach(explode("\n", $_POST["ignored"]) as $ignored2) {
      $ignored[] = $ignored2;
      if ( preg_match('/^[a-z]+$/i', $ignored2) ) {
         //do what you want...
      }
  }

UPDATE: Well, I found this answer, may be it's what you need:

Php Search_Array using Wildcard

Community
  • 1
  • 1
yarren
  • 23
  • 4
0

Here is a way to do it that can be customized fairly easily, using a lambda function:

$words = array('one','two','three','four');
$otherwords = array('three','four','five','six');

while ($word = array_shift($otherwords)) {
    print_r(array_filter($words, like_word($word)));
}

function like_word($word) {
    return create_function(
        '$a', 
        'return strtolower($a) == strtolower(' . $word . ');'
    );
}

http://codepad.org/yAyvPTIq

To add different checks, simply add more conditions to the return. To do it in a single function call:

while ($word = array_shift($otherwords)) {
    print_r(find_like_word($word, $words));
}

function find_like_word($word, $words) {
    return array_filter($words, like_word($word));
}

function like_word($word) {
    return create_function(
        '$a', 
        'return strtolower($a) == strtolower(' . $word . ');'
    );
}
Community
  • 1
  • 1
Jared Farrish
  • 48,585
  • 17
  • 95
  • 104