I have 2 to 3 strings.
example 1:
$a1 = 'a & b & c';
$a2 = 'b & c';
$a3 = 'c & a & b';
I want the common values as a delimited string.
$result = 'b & c'
If there are no intersections, the result should be an empty string.
I have 2 to 3 strings.
example 1:
$a1 = 'a & b & c';
$a2 = 'b & c';
$a3 = 'c & a & b';
I want the common values as a delimited string.
$result = 'b & c'
If there are no intersections, the result should be an empty string.
An approach using array_intersect in combination with explode, implode and array_map:
$a1 = 'a & b & c';
$a2 = 'b & c';
$a3 = 'a & b & c';
$result = implode(' & ',
call_user_func_array('array_intersect',
array_map(function($a) {
return explode(' & ', $a);
},
[$a1, $a2, $a3])
)
);
echo($result);
Or if you want to pass in an array directly:
$arr = ['a & b & c', 'b & c', 'a & b & c'];
$result = implode(' & ',
call_user_func_array('array_intersect',
array_map(function($a) {
return explode(' & ', $a);
},
$arr)
)
);
echo($result);
[$a1, $a2, $a3] in my method.$arr instead of [$a1, $a2, $a3].Use Array Intersect and unique for it
<?php
$a1 = 'a & b & c';
$a2 = 'b & c';
$a3 = 'a & b & c';
$pieces1 = str_word_count($a1, 1);
$pieces2 = str_word_count($a2, 1);
$pieces3 = str_word_count($a3, 1);
$result=array_intersect(array_unique($pieces1), array_unique($pieces2),array_unique($pieces3));
print_r ($result);
?>
o/p
Array ( [1] => b [2] => c )
For a dynamic script which can process any number of strings, pass your input data as a single array to the below. Use the spread operator to compare all sets of the exploded strings at once.
In short, explode all strings, retain all intersections, implode all survivors. Demo
echo implode(
' & ',
array_intersect(
...array_map(
fn($a) => explode(' & ', $a),
[$a1, $a2, $a3]
)
)
);
// b & c