-2

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.

1

3 Answers 3

7

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);
Sign up to request clarification or add additional context in comments.

6 Comments

hi there if i have an array for that what can i do like Array ( [0] => a & b & c [1] => a & b [2] => b [3] => a & b & c )
It's the same. I'm passing in array [$a1, $a2, $a3] in my method.
Can u show me that i am unable to do that can u please help me in that with passing an array as $arr
Just pass in $arr instead of [$a1, $a2, $a3].
i am getting a parse error Parse error: syntax error, unexpected T_FUNCTION, expecting ')'
|
0

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 )

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.