SitePoint Sponsor

Thread: checking in two arrays ??

1. checking in two arrays ??

Hello forums!!!
Case:
Suppose we have two arrays(returned by queries)
\$array1 and \$array2 of different sizes for example (two cases here)
a>
PHP Code:
``` \$array1 = array(1,2,3);\$array2 = array(1,2);  ```
b>
PHP Code:
``` \$array1 = array(1);\$array2 = array(1,2,4,5);  ```
I would like to check presence of any values of \$array1 in \$array2.
How to accomplish this, any ideas.
Thanks in advance for the suggestions.

2. Here it is for you:

Code PHP:
```foreach (\$array1 as \$item) {
if (in_array(\$item, \$array2)) {
//whatever you want to do here
}
}```

3. Note: size of two arrays are different . So you can't loop that way.

4. Why not? I am looping array1 only and checking if every element of array1 exists in array2

5. Actually PHPycho, the solution forkaya presented will work just fine. Array length is irrelevant.

Here is the code again:
Code:
```foreach (\$array1 as \$item) {
if (in_array(\$item, \$array2)) {
//whatever you want to do here
}
}```
What it will do is go through each element in the first array. It will then look and see if that element is found in array2. If it is, that value is present in both. If not, it isn't.

array_diff can also work. However, it would give you back any values not in both, not just those found in the first but not in the second.

So, for example, if we have the following:
Code:
```array1 = array(1,2,3,4,5);
array2 = array(4,5,6,7,8);```
The foreach solution would give you 4 and 5. The array_diff would give you 1,2,3,6,7,8.

6. array_intersect()

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•