Skip to content
Advertisement

Compare two arrays and create an associative array of true/false values

I want to compare the values of two flat, indexed arrays and generate a new array where the keys are the original values from the first array and the values are boolean values indicating whether the same value occurred in both origibal arrays.

JavaScript

I tried to compare the arrays with the array_diff() function but it gave me elements values instead of boolean values.

I want to compare each value from the two arrays and generate an “array map” or maybe using the array_combine() function to get array like this:

JavaScript

Advertisement

Answer

Arrays are fun!

PHP has a TON of array functions, and so there’s lots of potential solutions.

I came up with this one as a personal challenge, which uses no loops, filters, or maps.

This solution uses array_intersect to find values that exist in both arrays, then array_values along with array_fill_keys to turn them into associative arrays populated with TRUE or FALSE, and finally array_merge to put them together into a single array:

JavaScript

var_dump( $results ); results in:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement