Archimedees Posted October 8, 2007 Share Posted October 8, 2007 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 More sharing options...
TomKrush Posted October 8, 2007 Share Posted October 8, 2007 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); ?> Link to comment https://forums.phpfreaks.com/topic/72320-function-to-compare-arrays/#findComment-364658 Share on other sites More sharing options...
Archimedees Posted October 8, 2007 Author Share Posted October 8, 2007 Thanks TomKrush, Unfortunately your function just appends both arrays to each other. Please help me somebody. Link to comment https://forums.phpfreaks.com/topic/72320-function-to-compare-arrays/#findComment-364697 Share on other sites More sharing options...
kenrbnsn Posted October 8, 2007 Share Posted October 8, 2007 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 Link to comment https://forums.phpfreaks.com/topic/72320-function-to-compare-arrays/#findComment-364702 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.