In this article, we going to see how to achieve compare two comma-separated strings in PHP and keep only the values that appear in both. For that, we will be going to use PHP string and array function with the help of this we will get only intersected value in both the strings.
We going to see this step by step using an example for Compare 2 comma-separated strings in PHP:
Before discussion regarding this, first we will check which PHP string and array function going to use.
PHP string and array function we use are as follow as:
$string_one = "1,5,9,8,10".
$string_two = "1,3,9,10,20".
$show = "1,9,10".
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>contains demo</title> </head> <body> <?php $want_to_see = explode(",", "1,5,9,8,10"); $current_user_can_see = explode(",", "1,3,9,10,20") // Array of common elements: $show = array_intersect($want_to_see, $current_user_can_see); // If you want it as a string: $show_str = implode(",", $show); ?> </body> </html>
When we going to run this code in browser then you get output : “1,9,10”.
Now we will discuss regarding PHP string and array function. As there are many string and array function in php.But we going to check only above string and array function.
So let’s see to it step by step.
What is PHP explode() Function ?
PHP explode() Function Breaks the string into array.
Syntax is explode(separator,string,limit).Important point in this is “separator” parameter cannot be an empty string.
<?php $str = "Hello world. It's a beautiful day."; print_r (explode(" ",$str)); ?>
OUTPUT : Array (  => Hello  => world.  => It's  => a  => beautiful  => day. );
What is PHP implode() Function ?
PHP implode() Function Join array elements with a string.
Syntax is implode(separator,array).Important point in this is implode() function returns a string from the elements of an array.
<?php $arr = array('Hello','World!','Beautiful','Day!'); echo implode(" ",$arr); ?>
OUTPUT : Hello World! Beautiful Day!
DOWNLOAD PHP ONLINE JOB PORTAL PROJECT 100 % FREE
What is PHP array_intersect() Function ?
PHP array_intersect() Function Compare the values of two arrays, and return the matches.
Syntax is array_intersect(array1, array2, array3, …). An important point in this is function compares the values of two or more arrays, and returns an array that contains the entries from array1 that are present in array2, array3, etc. With the help of array intersect we can get intersected value.
I hope you liked my this article. If you have any queries or any question regarding this, Feel free to comment on Me.