1

It's another day for being thick—so sorry. :) Anyhow, I have 2 arrays that I want to manipulate; if a value from the first array exists in the second array do one thing and then do something else with the remaining values of the second array.

e.g.

$array1 = array('1','2','3','4'); - the needle
$array2 = array('1','3','5','7'); - the haystack

if(in_array($array1,$array2): echo 'the needle'; else: echo'the haystack LESS the needle '; endif;

But for some reason the in_array doesn't work for me. Help please.

1
  • Do you mean that "any value" or "all values" from the needle must be present in the haystack? Commented Sep 4, 2010 at 8:17

1 Answer 1

3

Do it like this:

<?php
$array1 = array('1','2','3','4');
$array2 = array('1','3','5','7');

//case 1:
print_r(array_intersect($array1, $array2));

//case 2:
print_r(array_diff($array2, $array1));
?>

This outputs the values of array (what you wanted earlier before question was changed):

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

And, if you want to use if-else, do it like this:

<?php
$array1 = array('1','2','3','4');
$array2 = array('1','3','5','7');

$intesect = array_intersect($array1, $array2);

if(count($intesect))
{
    echo 'the needle';
    print_r($intesect);
}
else
{
    echo'the haystack LESS the needle ';
    print_r(array_diff($array2, $array1));
}
?>

This outputs:

the needle
Array
(
    [0] => 1
    [2] => 3
)
3
  • Thanks shamittomar - said was being think, I couldn't get the first array into the array_diff as I had previously manipulated it somehow (forgotten now) as your code works a dream Commented Sep 4, 2010 at 8:15
  • If this is literally what you want, then array_diff is completely superfluous since you've already determined that the intersection is null. Commented Sep 4, 2010 at 8:19
  • @konforce, yes I agree but in the original question (which is now revised) it was asked to show the remaining values. Commented Sep 4, 2010 at 8:56

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.