0

I have an array

[
    [0 => 20, 1 => 36, 3 => 42],
    [0 => 21, 1 => 42, 2 => 30],
]

And I have a second array of

[24, 42, 26, 12] 

I want to use array_intersect() to get the values that are the same from each array. What I am having trouble with is figuring out how to properly set up the code to do that. I would hope to have this

[
    [42],
    [42],
]
0

1 Answer 1

1

To match your example output, you can simply use a foreach loop. In your example, the 2D array is $array1 and the 1D array is $array2.

$output = [];

foreach ($array1 as $array) {
    $output[] = array_intersect($array, $array2);
}

Note that declaring an array with [] is only supported in PHP versions >= 5.4. For PHP versions < 5.4:

$array1 = array(array(20, 36, 42), array(21, 42, 30));
$array2 = array(24, 42, 26, 12);

$output = array();

foreach ($array1 as $array) {
    $output[] = array_intersect($array, $array2);
}
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for the answer but that doesn't seem to work for me.
Could you share your output or error? Here's an example from the above code: eval.in/538917 If you don't want to preserve the keys, and need an output exactly matched to your question above, just add in array_values before array_intersect: eval.in/538918
I'm getting a syntax error, unexpected '[', I have done a direct copy and paste and just changed out my vars and can't get away from that error.
@ZacPaquette it is probably because your PHP version is older and does not understand the "new" array syntax. Try changing $output = []; to $output = array();.
@Don'tPanic is correct. PHP supports the shorthand declaration of arrays in version 5.4 or newer. I'll edit my answer to include the old version
|

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.