How to get the same value from two arrays in PHP?

后端 未结 6 879
小蘑菇
小蘑菇 2021-01-12 02:22

I want to get the same value from two arrays. Example:

a[] = array(a,b,c,d,e,f,g,h);
b[] = array(c,d,o,l,p,i,u,y);

I want c[]=c,d;

相关标签:
6条回答
  • 2021-01-12 02:27

    see http://docs.php.net/array_intersect:

    array_intersect() returns an array containing all the values of array1 that are present in all the arguments. Note that keys are preserved.
    $a = array('a','b','c','d','e','f','g','h');
    $b = array('c','d','o','l','p','i','u','y');
    $c = array_intersect($a, $b);
    var_dump($c);
    

    prints

    array(2) {
      [2]=>
      string(1) "c"
      [3]=>
      string(1) "d"
    }
    
    0 讨论(0)
  • 2021-01-12 02:28
    <?php
    
    $arr = array_intersect(array('a', 'b', 'c', 'd'),
                           array('c', 'd', 'e', 'f'));
    
    print_r(array_values($arr));
    
    0 讨论(0)
  • 2021-01-12 02:30

    Use array_intersect($a,$b) -- Ohh many guys answered before i typed

    0 讨论(0)
  • 2021-01-12 02:38

    You can use array_intersect() function.

    0 讨论(0)
  • 2021-01-12 02:43

    in_array() might be what you're looking for

    Use in_array() to see if the value you're looking for is in both arrays a and b and then put it in array c (following your example)

    http://www.php.net/manual/en/function.in-array.php

    0 讨论(0)
  • 2021-01-12 02:44

    Try $result = array_intersect($a, $b);

    0 讨论(0)
提交回复
热议问题