0

I have 2 arrays

First array  -- array1(3,17,19,11,34,56,22,29);
Second array -- array2(4,6,12,19,59,21);

Now I would like to get 3 types of data

a) values which are present in both array for eg `19`
b) values which are not present in array1 but present in array 2 for eg `4,6,12,59,21`
c) values which are not present in array2 but present in array 1 for eg `3,17,11,34,56,22,29`

Can it be done using a single for() loop?

2 Answers 2

6

The PHP docs are your friend

PHP has a bunch of built in functions for working with arrays

The full list is here: http://www.php.net/manual/en/ref.array.php

The ones you're after are array_intersect and array_diff

Look mum, no loop!

a) array_intersect($array1, $array2)

b) array_diff($array1, $array2)

b) array_diff($array2, $array1)

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

7 Comments

I think each function will take one loop. So its 3 loop. May be he is looking for manual solution and not using the in-build function.
Thanks.Actually right it can be done using inbuilt function.But what I have said is if this can be achieved using single 'for loop'.
Why would you want to reinvent the wheel?
Well the thing is instead of running 3 loops to perform some sqls isn't it better to get it done using one loop and thus it takes less time?
ok lets forget about the sql.I would like to get the same output but using a single for loop.
|
0

Try array_merge:

array_unique(array_merge($array1, $array2));

1 Comment

Sorry Pathik as I would like to achieve the same thing using for loop instead using inbuilt functions.

Your Answer

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