w3resource

PHP Array Exercises : Merge two commas separated lists with unique value only


43. Merge Two Comma-Separated Lists with Unique Values

Write a PHP script to merge two commas separated lists with unique value only.

Sample Solution:

PHP Code:

<?php
// Define two comma-separated lists as strings
$list1 = "4, 5, 6, 7";
$list2 = "4, 5, 7, 8";

// Combine both lists with unique values only
// Explode the strings into arrays, merge them, remove duplicates, and implode back into a string
$result = implode("," , array_unique(array_merge(explode(",",$list1),explode(",", $list2))));

// Display the result
echo $result."\n";
?>

Output:

4, 5, 6, 7, 8

Flowchart:

Flowchart: PHP - Merge two comma separated lists with unique value only

PHP Code Editor:

For more Practice: Solve these Related Problems:

  • Write a PHP script to take two comma-separated strings, merge them, and output a list of unique values separated by commas.
  • Write a PHP function to parse two CSV strings, combine their elements, remove duplicates, and join them back to a string.
  • Write a PHP program to merge two lists provided as strings and then use array_unique() to filter the merged values.
  • Write a PHP script to concatenate two comma-separated lists, split them into an array, remove duplicate entries, and display the result.

Go to:


PREV : Unique Flattened Values from Multidimensional Arrays.
NEXT : Remove Specified Duplicate Entry from Array.



Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.