PHP array_intersect()

array_intersect() function returns the shared elements of array1 and other arrays.
   array array_intersect(array array 1, array array 2 [, array ...])

<?PHP
	$arr1=array(1,2,3,4,5,6,7,8,9);
	$arr2=array(2,4,6,8);
	$arr3=array_intersect($arr1,$arr2);
	foreach($arr3 as $element) echo "$element, "; //2, 4, 6, 8,
?>

If more than 2 arrays are compared, only elements contained in all arrays will be returned.

<?PHP
	$arr1=array(1,2,3,4,5,6,7,8,9);
	$arr2=array(2,4,6,8);
	$arr3=array_intersect($arr1,$arr2,array(2,4));
	foreach($arr3 as $element) echo "$element, "; //2, 4
?>

It can also take associative arrays, both the keys and values will be compared.

<?PHP
	$arr1=array("apple"=>2.2,"rice"=>0.5,"nuts"=>4.99,"meat"=>6.99);
	$arr2=array("apple"=>1.2,"rice"=>0.5,"orange"=>1.99);
	$arr = array_intersect($arr1,$arr2);
	print_r($arr);

    //the result is:
	Array
	(
		[rice] => 0.5
	)
?>

array_diff() function compares arrays and returns all the elements in the 1st array but not in the 2nd array.

<?PHP
	$arr1=array(1,2,3,4,5,6,7,8,9);
	$arr2=array(2,4,6,8);
	$arr3=array(1,3);
	$arr=array_diff($arr1,$arr2,arr3);
	foreach($arr as $element) echo "$element, "; //5, 7, 9, 
?>

array_intersect_key() function compares array keys and returns all the elements in the 1st array as well as in the following arrays.

<?PHP
	$arr1=array("apple"=>2.2,"rice"=>0.5,"nuts"=>4.99,"meat"=>6.99);
	$arr2=array("apple"=>1.2,"rice"=>0.5,"orange"=>1.99);
	$arr = array_intersect_key($arr1,$arr2);
	print_r($arr);
	
	//the result is:
	Array
	(
		[apple] => 2.2
		[rice] => 0.5
	)	
?>




:: PHP Tutorials Home ::
PHP String Functions
 • concatenation • echo
 • ereg • ereg_replace
 • explode • htmlspecialchars
 • preg_match • preg_replace
 • preg_split • print,sprintf
 • str_replace • strcmp
 • strpos • strrev
 • strrpos • strtr
 • substr • substr_replace
PHP Array Functions
 • array_diff • array_flip
 • array_intersect • array_key_exists
 • array_keys • array_merge
 • array_pop • array_push
 • array_rand • array_search
 • array_splice • array_unshift
 • array_values • asort & arsort
 • count • in_array
 • ksort • shuffle
 • sort
PHP Data Types
 • array • associative array
 • date & time • number
 • class, object • regular expression
 • string • variables
PHP Loop & Conditions
 • continue & break • for loop
 • foreach • if else
 • not equal • while
PHP File System Functions
 • copy • delete, unlink
 • dirname • download url
 • file_exists • is_file
 • mkdir • read file
 • scandir • write file
PHP Popular Topics
 • ajax • clone
 • comments • constants
 • cookie • database
 • defined • die
 • form validation • gd, draw images
 • global variables • header url
 • heredoc • mail
 • pass by reference • print
 • regular expression • sessions
 • threads • xml parse
PHP Math Functions
 • abs • cos
 • exp • floor & ceil
 • fmod • log
 • max & min • pow
 • round • sin
 • sqrt • tan
convert.idontcarewhatyouthink.net © 2021  Terms of Use | Home