Skip to content
Advertisement

Merge Arrays But Join Corresponding Keys

I am trying to achieve the following functionality:

There is 5 textareas, the user inputs several words on different lines into the textarea, on click of a button it creates arrays from these textareas and the merges the array whilst appending the corresponding keys.

Textarea 1:

example 1

example 1 other

Textarea 2:

example 2

example 2 other

Using:

$col1 = $_POST['txta1']; $col1Array = explode("n", str_replace("r", "", $col1));            
$col2 = $_POST['txta2']; $col2Array = explode("n", str_replace("r", "", $col2));

This will now give me an array for each keyword, separating the textarea value based on a new line.

I now want to combine the 2 arrays so that key [0] appends the first array and so on, it should become

array([0]=>'example 1 example 2',[1]=>'example 1 other example 2 other');

In order for me to the echo out into another textarea, the results whilst should be:

example 1 example 2

example 1 other example 2 other

Advertisement

Answer

You can pass both the arrays to array_map to pivot them into the format you want, then implode the inner arrays so you end up with an array of strings rather than an array of arrays.

$result = array_map(
    function(...$row) { return implode(' ', $row); },
    $col1Array, $col2Array
);
2 People found this is helpful
Advertisement