1

I have 3 arrays, in this way:

$add[] = carblue,carred,bus;
$allad[] = car,carblue,carred,bus;
$fis[] = bus,car;

now i write this code:

foreach($add as $ad) {
   foreach($fis as $fisvalue) {
      if (in_array(substr($fisvalue, 0, strlen($ad)), $allad)) {
         echo $fisvalue;
      }
   }
}

But result of this code is:

bus
car
bus
car
bus
car
car

I want just echo "bus car" and the otherhand seems using two foreach necessary! Can you have idea to solve my problem and echo just?:

car
bus

in other word, if value of $allad[] starting with $fis[] value echo $fis[] value but just once, with out repeating!

RDK
  • 4,540
  • 2
  • 20
  • 29
MAND
  • 55
  • 6
  • http://stackoverflow.com/questions/5808923/filter-values-from-an-array-similar-to-sql-like-search-using-php – pbaldauf Jan 26 '15 at 08:28
  • 1
    That code in the beginning is not valid PHP; if it's supposed to be pseudo code, is anyone's guess what it really represents. Hence we have no real idea what your array really looks like. – deceze Jan 26 '15 at 08:31

3 Answers3

1

Use this, it will give you what you want.

<?php
$add=array('carblue','carred','bus');
$allad=array('car','carblue','carred','bus');
$fis=array('bus','car');

$outputValue = array();
foreach($add as $ad) {
    foreach($fis as $fisvalue) {
        if (in_array(substr("$fisvalue",0,strlen("$ad")),$allad)){
            $value = $fisvalue;
            if ( !in_array($value,$outputValue) )  $outputValue[] = $value;
        }
    }
}

echo implode($outputValue, ', ');
?>
abbas
  • 238
  • 2
  • 18
0

first of all, why you need $add array if you want to echo $fis if $allad value starts with $fis value ? This code works:

$add = array('carblue','carred','bus');
$allad = array('car','carblue','carred','bus');
$fis = array('bus','car');

foreach($fis as $fisvalue) {

        foreach($allad as $ad) {

            if (strpos($ad,$fisvalue) === 0){             
               $matched = true;
            }
        }
        if ($matched) {
           $matched = false;
           echo $fisvalue;
        }
    }

first we iterate values that we want to echo once, then we compare those values with array $allad, if $fisvalue found in $ad at place 0 (start) then mark as matched, and if $fisvalue is matched then echo it

szapio
  • 998
  • 1
  • 9
  • 15
0

You can do something like this

$foundResults = array(); # you will save here every result you have found
foreach($add as $ad) {
   foreach($fis as $fisvalue) {
      if (in_array(substr($fisvalue, 0, strlen($ad)), $allad)) {
        if(!in_array($foundResults)) # if result doesn't exist in $foundResults, then echo result and add it to the $foundResults array
          echo $fisvalue;
          array_push($foundResults, $fisvalue);
      }
   }
}
Branimir Đurek
  • 632
  • 5
  • 13