How to compare two arrays and generate new array with common elements from both arrays in PHP?
There exists the php inbuilt function called array_intersect that computes the intersection of arrays.
Syntax:
Example of array_intersect()
Source: http://php.net/manual/en/function.array-intersect.php
Syntax:
array array_intersect ( array $array1 , array $array2 [, array $ ... ] ) //array 1: An array with master values to check. //array 2: An array to compare values against. //Returns an array containing all of the values in array1 whose values exist in all of the parameters.array_intersect() returns an array containing all the values of array1 that are present in all the arguments. Note that keys are preserved.
Example of array_intersect()
<?php $array1 = array("a" => "green", "red", "blue"); $array2 = array("b" => "green", "yellow", "red"); $result = array_intersect($array1, $array2); print_r($result); ?>The above example will output:
Array ( [a] => green [0] => red )In this way, you can generate array which has common elements from both arrays. :)
Source: http://php.net/manual/en/function.array-intersect.php
Comments
Post a Comment