1

I have two arrays:

$userBuildingIds

print_r():

Array
(
    [0] => 4
 )

and $allRequiredIds

print_r:

Array
(
    [0] => 4
    [1] => 1
)

now I want check if one element of $userBuildingIds exists in the $allRequiredIds array. And if so, I want get a new array of all elements they are NOT in the first array like this:

Array
(
    [0] => 1
)

(because 1 isn't in $userBuildingIds) I try this with array_diff but it gives me this result (with the key of array 2):

Array
(
    [1] => 1
)

Is it possible to get an array in which are all the elements of array $allRequiredIds where are not in $userBuildingIds, but without copy the keys from $allRequiredIds?

3
  • If you don't care about the keys of the returned array then you can just use array_values() on it to get a new array having the keys starting with 0. So, the complete code will be array_values(array_diff($allRequiredIds, $userBuildingIds)). Commented Jan 29, 2015 at 14:39
  • thanks, this will work.. you can answer this, so I can accept your answer. Commented Jan 29, 2015 at 14:42
  • I am not sure what are you trying to achive and how different values could be in your array. but I am sure you know that for $arr1 = [1,1,1,1,1]; $arr2 = [1,2]; array_diff($arr1, $arr2); will return emty array? that is really your point? Commented Jan 29, 2015 at 14:50

1 Answer 1

3

If you don't care about the keys of the returned array then you can just use array_values() on it to get a new array having the keys starting with 0.

The code will be:

$diffIds = array_values(array_diff($allRequiredIds, $userBuildingIds));

It produces a list of values from $allRequiredIds that does not exist in $userBuildingIds. The returned list has numeric keys starting with 0 (no association with the original keys from $allRequiredIds is $userBuildingIds is kept, on purpose).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.