Reputation: 55
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!
Upvotes: 1
Views: 84
Reputation: 1008
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
Upvotes: 0
Reputation: 632
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);
}
}
}
Upvotes: 0
Reputation: 228
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, ', ');
?>
Upvotes: 1