Jump to content

function to compare arrays


Archimedees

Recommended Posts

 

I have two arrays  for instance

 

$arLetters = array ("a", "c", "d", "e", "Z", U");

$arNewLetters = array ("a", "g", "p", "n", "Z");

 

Now I want a function that creates an array with all the values in both arrays (once)

 

$arNewerLetters = array ("a", "c", "d", "e", "g", "n", "p", "U", "Z");

 

 

Which function to use?

Thanks

Link to comment
https://forums.phpfreaks.com/topic/72320-function-to-compare-arrays/
Share on other sites

I was thinking there was a predefined function to do this but I guess not.  Below is a simple method using array_merge and array_unique.

 

<?php
$arLetters = array("a", "c", "d", "e", "Z", "U");
$arNewLetters = array("a", "g", "p", "n", "Z");

$newArray = array_merge($arLetters, $arNewLetters);
$newArray = array_unique($newArray);

print_r($newArray);
?>

 

If you would like it to be a function here you go.

 

<?php
//Merges two arrays and makes sure each value is unqiue
function array_merge_unique($array1, $array2) {
	//Makes sure both arrays are of the type array
	if(!is_array($array1) || !is_array($array2)) {
		return 0;
	}

	return array_unique(array_merge($array1, $array2));
}

$arLetters = array("a", "c", "d", "e", "Z", "U");
$arNewLetters = array("a", "g", "p", "n", "Z");

$newArray = array_merge_unique($arLetters, $arNewLetters);

print_r($newArray);
?>

His function seems to work correctly. What results are you getting? What are you expecting?

 

When I run it, I get the following:

Array
(
    [0] => U
    [1] => Z
    [2] => a
    [3] => c
    [4] => d
    [5] => e
    [6] => g
    [7] => n
    [8] => p
)

 

I sorted the array before printing it.

 

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.