Search code examples
phparraysstringstring-concatenation

How do I concatenate each the values of a variable1 with each values of variable2


// a simpler thing that would get me what I need is: How do I concatenate each the values of a variable1 with each values of variable2

$Var1 = 'my1, my2, my3'; // here I have dozens of entries, they are    symbols
$Var2 = 'word1, word2, word3'; // here also dozens of entries, are words.

How do I have all the keys of a variable, placed together of the keys of another variable?

$Values_that_I_needed = 'my1word1, my1word2, my1word3, my2word1, my2word2, my2word3, my3word1, my3word2, my3word3'; 

How would I build this values this variable up with all those values without having to type everything!?

Imagine an example with 60 my1, my2 … and 130 word1, word2 …. it’s my case! Put each of the 60my before each of the 130 words !! // I need to concatenate / join / join each values / keys of a variable, with all the values/keys of another variable, to avoid making all these combinations by hand. and put in another variable.


Solution

  • The solution using explode and trim functions:

    $Var1 = 'my1, my2, my3'; // here I have dozens of entries, they are    symbols
    $Var2 = 'word1, word2, word3';
    $result = "";
    $var2_list = explode(',', $Var2);
    
    foreach (explode(',', $Var1) as $w1) {
        foreach ($var2_list as $w2) {
            $result .= trim($w1) . trim($w2). ', ';
        }
    }
    $result = trim($result, ', ');
    print_r($result);
    

    The output:

    my1word1, my1word2, my1word3, my2word1, my2word2, my2word3, my3word1, my3word2, my3word3