Home > Back-end >  Searching $haystack with 2 different potential matches
Searching $haystack with 2 different potential matches

Time:08-04

I have a given array:

$array = array('one','two','three_num3','four');

and a dynamic variable:

$term = $_GET['term'];

I'm currently using array_search() to search $array:

$target = array_search($term,$array);
if ($target > -1) {
  echo $target;
} else {
  echo 'No Target Result';
}

$target yields no result if $term is just 'three' or 'num3'.

I want to be able to find 'three_num3' in the $array where $term is either 'three' or 'num3' and is a match for 'three_num3'.
In other words, I want the underscore to act as a sort of divider, but effectively remain as one string.

Any simple way to go about this?

CodePudding user response:

You can use this loop for this

your code is

$array = array('one','two','three_num3','four');
$term = $_GET['term'];

if(in_array($term,$array)){
    echo $term;
}

foreach($array as $key=>$value){
    $ex_val=explode('_',$value);
    if(count($ex_val) == 2){
           if($term == explode('_',$value)[0]){
       echo $array[$key];
    }elseif($term ==explode('_',$value)[1]){
        echo $array[$key];
    }
    }

}

CodePudding user response:

You can use array_filter with custom function :) array_search checks full value in array props

  • Related