I have array for example:
$myArr1 = array(
"word1" => "hello",
"word2" => "hi",
"word3" => "welcome",
);
$myArr2 = array(
"word1" => "hello",
"word3" => "welcome",
"word2" => "hola"
);
How to make join duplicate keys "word" and if there are duplicates join it values to get output:
"word1" => "hello",
"word2" => "hi hola",
"word3" => "welcome"
How about making a function?
function pushWordToArray($arr,$word,$key)...
in the function you would then check if the $key already exists and then concat the existing word and the $word you're inputting.
EDIT:
Answer to the edited question.
Just run through the both arrays and concat the two duplicate keys (if any).
Try this to get the result
$myArr1 = array(
"word1" => "hello",
"word2" => "hi",
"word3" => "welcome",
);
$myArr2 = array(
"word1" => "hello",
"word3" => "welcome",
"word2" => "hola"
);
$myArr3 = merge_duplicate_values($myArr1,$myArr2);
function merge_duplicate_values($myArr1,$myArr2){
$myArr3=array_merge_recursive($myArr1,$myArr2);
foreach($myArr3 as $key => $val){
if(is_array($val)){
$myArr3[$key] = implode(' ',array_unique($val));
}
}
return $myArr3; // its your desired result
}
$result = array();
foreach($myArr1 as $k=>$v) {
if($myArr1[$k] == $myArr2[$k])
{
$result[] = $v;
}
else
{
$result[] = $v.' '.$myArr2[$k];
}
}
print_r($result);
Loop the values against the other one, append if needed. You can do something like:
$myArr1 = array(
"word1" => "hello",
"word2" => "hi",
"word3" => "welcome",
);
$myArr2 = array(
"word1" => "hello",
"word3" => "welcome",
"word2" => "hola"
);
foreach($myArr2 as $key => &$value) {
if($myArr1[$key] != $myArr2[$key]) {
$myArr1[$key] .= ' '.$value;
}
}
print_r($myArr1);
Should output:
Array
(
[word1] => hello
[word2] => hi hola
[word3] => welcome
)
$myArr3 = array_merge_recursive($myArr1, $myArr2);
foreach($myArr3 as $key => $value){
if(!is_array($myArr3[$key])){
continue;
}
if($value[0] === $value[1]){
$myArr3[$key] = $value[0];
}else{
$myArr3[$key] = implode(' ', $value);
}
}
// print_r($myArr3);