SitePoint Sponsor

User Tag List

Results 1 to 7 of 7
  1. #1
    SitePoint Wizard PHPycho's Avatar
    Join Date
    Dec 2005
    Posts
    1,201
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    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. #2
    SitePoint Enthusiast
    Join Date
    Nov 2008
    Location
    New York
    Posts
    90
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Here it is for you:

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

  3. #3
    SitePoint Wizard PHPycho's Avatar
    Join Date
    Dec 2005
    Posts
    1,201
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Note: size of two arrays are different . So you can't loop that way.

  4. #4
    SitePoint Enthusiast
    Join Date
    Nov 2008
    Location
    New York
    Posts
    90
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Why not? I am looping array1 only and checking if every element of array1 exists in array2

  5. #5
    SitePoint Addict silentcollision's Avatar
    Join Date
    Jun 2006
    Location
    New Zealand
    Posts
    388
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

  6. #6
    SitePoint Wizard
    Join Date
    Dec 2003
    Location
    USA
    Posts
    2,582
    Mentioned
    29 Post(s)
    Tagged
    0 Thread(s)
    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.

  7. #7
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2008
    Posts
    5,757
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    array_intersect()


Bookmarks

Posting Permissions

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