开发者

Want to got the new array that not in array A?

开发者 https://www.devze.com 2023-01-12 16:54 出处:网络
I have two arrays: $A = array(\'a\',\'b\',\'c\',\'d\') $c = array(\'b\',\'c\',\'e\',\'f\') I want to get a new array containing items not in array $A. So it开发者_JS百科 would be:

I have two arrays:

$A = array('a','b','c','d')
$c = array('b','c','e','f')

I want to get a new array containing items not in array $A. So it开发者_JS百科 would be:

$result = array('e','f');

because 'e' and 'f' are not in $A.


Use array_diff
print_r(array_diff($c, $A)); returns

Array
(
    [2] => e
    [3] => f
)


Use array_diff for this task. As somewhat annoying it does not return all the differences between the two arrays. Only the elements from the first array passed which are not found in any other array passed as argument.

$array1 = array('a','b','c','d');
$array2 = array('b','c','e','f');
$result = array_diff($array2, $array1);


array_diff()


Pseduo Code for General Implementation

Disclaimer: Not familiar with PHP, other answers indicate there are a lot quicker ways of doing this :)

Loop through your first array:

// Array of results
array results[];

// Loop through all chars in first array
for i = 0; i < A.size; i++
{
    // Have we found it in second array yet?
    bool matched = false;

    // Loop each character in 2nd array
    for j = 0; j < C.size; j++
    {
        // If they match, exit the loop
        if A[i] == C[J] then
            matched = true;
            exit for;
    }

    // If we have a match add it to results
    if matches == true then results.add(A[i])

}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号