Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.