PHP根据另一个数组中的选定元素消除数组元素

时间:2014-05-07 06:26:58

标签: php arrays

我有这些数组:

$a = array(1,2,3,4,5,6,7);

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
)

$b = array(2,3);

Array
(
    [0] => 2
    [1] => 3
)

我想从数组$a中包含的数组$b中删除元素。所以结果就像:

$c = array(1,4,5,6,7);

Array
(
    [0] => 1
    [1] => 4
    [2] => 5
    [3] => 6
    [4] => 7
)

有没有PHP函数可以做到这一点?谢谢

2 个答案:

答案 0 :(得分:4)

使用array_diff()

$result = array_diff($a, $b);

测试:

print_r(array_diff([1,2,3,4,5,6,7], [2,3]));

输出:

Array
(
    [0] => 1
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
)

答案 1 :(得分:2)

Try array_diff() funciton

$c = array_diff($a, $b);