Jump to content

Searching an array problem


kapz22

Recommended Posts

Hi,

 

i want to search an array with another array; i have producd the follwing code, but i am having some problems with it.

 

foreach ($array1 as $value) {
if (in_array($value, $array2)) {
	echo "In Array";
} else {
	echo "Not In Array";
}

}

 

this code works fine, however, once it finds an exisitng value, it does not reset, so it will go to the next value in array2 and it will say "In Array" even though it does not exist.

 

What have i done wrong?

 

Please help.

 

 

Link to comment
https://forums.phpfreaks.com/topic/194071-searching-an-array-problem/
Share on other sites

Yes, please explain a little better what you are trying to do. If you are just wanting to check if any element in array1 exists in array2, then you don't need to iterate over each element, just use array_interset(). Or, depending upon your need you could use array_diff (or any of the variants of those two functions):

 

if (count(array_intersect($array1, $array2))>0)
{
    echo "At least 1 item in array 1 exists in array 2.<br>";
    echo "They are: " . print_r(array_intersect($array1, $array2));
}
  
if (count(array_diff($array1, $array2))==0)
{
    echo "All the items in array 1 exists in array 2.";
}

The foreach loop is within a While loop

basiclly i have 2 values in array1 and 10 values in array2

 

So currently i am getting the follwing:

 

Not In Array

Not In Array

Not In Array

Not In Array

In Array

In Array

In Array

In Array

In Array

In Array

 

It should ready:

 

Not In Array

Not In Array

Not In Array

Not In Array

In Array

Not In Array

Not In Array

Not In Array

In Array

Not In Array

 

 

For some reason once it finds the 1st value, then it keeps on saying "In Array". even though the value does not exist.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.