Question

I have two arrays $t1 and $t2. When I print them out I get the following:

t1:

Array ( [0] => Christina Aguilera [1] => Iron Maiden [2] => Bob Marley ) 

t2:

Array ( [0] => Bob Marley )

I'm trying to get the common elements of the array though the array_intersect function, and I'm using the below line:

$intersection = array_intersect($t1,$t2);

However, for some reason when I print the result $intersection I get get:

Array ( )

Can anybody see what it is going wrong? The code for my function is below but I think the above should be sufficient to work it out.

// For extra information
function findMutualInterests($_uProArray, $_tProArray)
{
    $_commonDetails = null;

    $_fieldNames = array_keys($_uProArray[0]);
    $_uProValues = array_values($_uProArray[0]);
    $_tProValues = array_values($_tProArray[0]);
    //print_r($_uProValues);

    // Iterate over the arrays and find ones in common
    for ($i = 0; $i < count($_uProValues); $i++) {
        $t1 = explode(',',$_uProValues[$i]);
        print_r($t1);
        $t2 = explode(',',$_tProValues[$i]);
        print_r($t2);
        $intersection = array_intersect($t1,$t2);
        print_r($intersection);
        $_commonDetails[$_fieldNames[$i]] = implode($intersection);
    }
    return $_commonDetails;
}

EDIT: Just thought I would point out that the output of $t1 and $t2 shown above are the output of a single iteration of the below function. I just chose that one as an example.

Was it helpful?

Solution

Your code works fine, try trimming input strings.

OTHER TIPS

Your code has a huge mistake. If you have more elements in $_tProValues than in $_uProValues you will not test all possibilities in the $_tProValues array. Then you'll not be able to test all possibilities. What happens here is exactly that, you're not testing all possibilities.

Check the comments above, because this works just fine:

<?php

$a = array (
        0 => 'Christina Aguilera',
        1 => 'Iron Maiden',
        2 => 'Bob Marley'
    );

$b = array (
        0 => 'Bob Marley'
    );

$intersect = array_intersect( $a, $b );

print_r( $intersect );

?>

Output:

Array
(
    [2] => Bob Marley
)
**Check the code it is very useful for you ,because this works fine:**

$final_arr = [];
foreach ($a as $a_val) {
      foreach ($b as $b_val) {
        if(in_array(strtolower($a), array_map('strtolower', $b_val))){
            $final_arr[] = $b_val; 
            }
       }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top