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.

$array1 = [
    "car1",
    "car2",
    "car3",
    "car4",
    "car5"
];

$array2 = [
    "car1",
    "car4",
    "car5"
}

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:

[
    "car1" => true,
    "car2" => false,
    "car3" => false
    "car4" => true,
    "car5" => true,
]

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:

$array1 = array( 0 => "car1", 1 => "car2", 2 => "car3", 3 => "car4", 4 => "car5");
$array2 = array( 0 => "car1", 1 => "car4", 2 => "car5" );

// Find all values that exist in both arrays
$intersect = array_intersect( $array1, $array2 );
// Turn it into an associative array with TRUE values
$intersect = array_fill_keys( array_values($intersect), TRUE );
// Turn the original array into an associative array with FALSE values
$array1 = array_fill_keys( array_values( $array1 ), FALSE );

// Merge / combine the arrays - $intersect MUST be second so that TRUE values override FALSE values
$results = array_merge( $array1, $intersect );

var_dump( $results ); results in:

array (size=5)
  'car1' => boolean true
  'car2' => boolean false
  'car3' => boolean false
  'car4' => boolean true
  'car5' => boolean true
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement