Jump to content

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.