user874737
user874737

Reputation: 533

Find same value PHP array

I have two arrays, I need to find out the value for each of the array which is the same.

For example,

   $arr1=array("a", "b", "c");
   $arr2=array("c", "d", "e");

Then c should be display. How could I do this?

Upvotes: 1

Views: 4442

Answers (3)

Daxen
Daxen

Reputation: 527

$word1 =array('a', 'b','c', 'd');
$word2 =array('b', 'c', 'd', 'a');
$data = array_intersect($word1, $word2);

it will return a,b,d because that is common in both array

print_r( $data );
/* result:
    Array (
             [0] => a
             [1] => b
              [3] => d 
    ) */

Upvotes: 1

Philippe
Philippe

Reputation: 9752

If you want to do it "manually", here is one way:

$a1 = array("a", "b", "c");
$a2 = array("c", "d", "e");

$a3 = array();
foreach($a1 as $x) foreach($a2 as $y) if($x == $y) $a3[] = $x;

print_r($a3);
// prints:
// Array
// (
//    [0] => c
// )

Upvotes: 0

codaddict
codaddict

Reputation: 455092

You can use the array_intersect function to find common elements.

Upvotes: 2

Related Questions