2

Is it possible to implode multiple array values?

From what I have researched so far, all the examples include imploding multi dimensional arrays (using array_map) or imploding all values from an array using implode(',', $array);

However, I would like to know if there is a way to implode array values from an array:

array([0] (
   array [0] ([0] A, [1] B, [2] C, [3] H)
   array [1] ([0] A, [1] D, [2] G, [3] H, [4] L)
   array [2] ([0] D, [1] Z, [2] J, [3] K, [4] O, [5] X)
)
array([1] (
   array [2] ([0] F, [1] Y, [2] W, [3] H, [4] L)
)
array([2] (
   array [0] ([0] O, [1] T, [2] C, [4] O, [5] X)
   array [1] ([0] U, [1] E, [2] E, [3] D)
))

Note: the strings in each array can be repeated several times and it has no bearing on the outcome.

Desired Outcome

to arrive at a result that looks like this:

$result = array(
          array [0] (A_C, B_H, C)
          array [1] (A_G, D_H, G_L)
          etc...

The expected results should allow me to test, IF the value cannot be combined (because it is at the end of the array), then display the single value

Being a beginner, my first resort was to try out implode implode($array[0], '_', $array[2]);
but I found out it does not work as 2 parameters are allowed

4
  • 3
    vague question. Please mention scenario and expected pattern. Commented Jun 21, 2016 at 5:03
  • 1
    Telling us you tried to use three parameters for a 2 parameter function just tells us that you're very confused, which can only confuse us. Commented Jun 21, 2016 at 5:06
  • 1
    Pretty Unclear What you want to achieve over here Commented Jun 21, 2016 at 5:07
  • please post your initial array fully and your expected outcome also. you made everyone confused and we are only guessing. Please do it Commented Jun 21, 2016 at 7:19

5 Answers 5

4

Some examples to use implode in multidimensional array

$sampleArray = array(array('abc', 'def', 'hij'), array('mno', 'xxy', 'kkl'));
foreach($sampleArray as $key => $val) {
    $impArray = array($val[0], $val[2]);
    echo implode('_', $impArray);
}


-- -- -- -- -- -Dynamic implode with array first and last value-- -- -- -- -

$sampleArray = array(array('abc', 'def', 'hij'), array('mno', 'xxy', 'kkl'));
foreach($sampleArray as $key => $val) {
    $count = count($val);
    if ($count > 1) {
        $first = reset($val);
        $last = end($val);
        $impArray = array($first, $last);
    } else {
        $first = reset($val);
        $impArray = array($first);
    }

    echo implode('_', $impArray);
}

-- -- -- -- -- -- -- -- -- -- -- -Fully Dynamic with odd, even rules-- -- -- -- --

$finalArray = array();
$sampleArray = array(array('abc', 'def', 'hij', 'dsfd', 'fff'), array('mno', 'xxy', 'kkl'));
foreach($sampleArray as $key => $val) {
    $oddEvenArr = make_array_odd_even($val);
    if (!empty($oddEvenArr['odd']) || !empty($oddEvenArr['even'])) {
        $findMaxSize = 0;
        $oddSize = count($oddEvenArr['odd']);
        $evenSize = count($oddEvenArr['even']);
        if ($oddSize > $evenSize) {
            $findMaxSize = $oddSize;
        } else {
            $findMaxSize = $evenSize;
        }
        for ($i = 0; $i < $findMaxSize; $i++) {
            if (array_key_exists($i, $oddEvenArr['even'])) {
                $finalArray[$key][] = implode('_', $oddEvenArr['even'][$i]);
            }
            if (array_key_exists($i, $oddEvenArr['odd'])) {
                $finalArray[$key][] = implode('_', $oddEvenArr['odd'][$i]);
            }
        }
    }
}

function make_array_odd_even($temp) {
    $odd = array();
    $even = array();
    foreach($temp as $k => $v) {
        if ($k % 2 == 0) {
            $even[] = $v;
        } else {
            $odd[] = $v;
        }
    }
    $oddChunk = array_chunk($odd, 2);
    $evenChunk = array_chunk($even, 2);
    return array('odd' => $oddChunk, 'even' => $evenChunk);
}
echo "<pre>";
print_r($finalArray);
die;
Sign up to request clarification or add additional context in comments.

5 Comments

thanks, your solution works. How would you do though if the array had more than 3 values and I needed to loop all of them with the same pattern e.g. array(array( abc_ghi, def_jkl), array(mno_stu, pqr_vwx, BCD_HIJ) ?
Okay give me some time i am updating with these answer
Hi, thanks for the revised code but that does not quite work. it takes the first and last value of the second array, whereas I need to concatenate every second value of the array as follow: array( array (1_3, 2_4, 5_7, 6_8), array (1_3, 2_4))
also the arrays may not all be the same length
hi can you recheck with last one code "Fully Dynamic with odd,even rules"
1
<?php
$a = array('abc','def','ghi');
$b[0]=$a;

foreach($b as $key=>$val){ 
    array_splice($val, 1, 1);
    $val=implode('_', $val);
    $output[$key]= $val;
    echo $val;
}
var_dump($output);
?>

Would you please try this ? With $Output you will be get array of desire output so you can use it for array which has multiple element like this as well. :)

2 Comments

Would you please check $b ?
Hello, thanks your answer almost works; it does not seem to work. Array to string conversion error
0

You can use below script:

$result = $array[0][0].'_'. $array[0][2];
echo $result;

Output:

abc_ghi

Comments

0

You can try:

$array = array(0 => "abc", 1 => "zyx", 2 => "bcf", 3 => "jhf");

$output = array();
for ($i = 0; $i < count($array); $i++)
{
  $output[] = $array[$i] . "_" . $array[$i+2];
}
var_dump($output);

Returns:

array(4) {
  [0]=>
  string(7) "abc_bcf"
  [1]=>
  string(7) "zyx_jhf"
  [2]=>
  string(4) "bcf_" // $i+2 issue
  [3]=>
  string(4) "jhf_" // $i+2 issue
}

This is bad though, for example when you're on the second last entry+ of $array there is no $i+2

2 Comments

He can throw it in a foreach loop if he wants, just giving guidance.
A check:- if(isset($array[$i+2])){$output[] = $array[$i] . "_" . $array[$i+2];} will remove i+2 issue as well as the last two weird output "bcf_" and "jhf_"
0

I thought I would take the opportunity to provide a refined answer to your updated input data. I think this is a simpler method anyhow.

See inline comments for explanation.

Code: (Demo)

$array=[
    [
        ['A','B','C','H'],
        ['A','D','G','H','L'],
        ['D','Z','J','K','O','X']
    ],
    [
        2=>['F','Y','W','H','L']
    ],
    [
        ['O','T','C','O','X'],
        ['U','E','E','D']
    ]
];

foreach($array as $k1=>$lev2){
    foreach($lev2 as $k2=>$lev3){
        foreach($lev3 as $i=>$v){
            if(isset($lev3[$i+2])){ // if can be paired with desired value 
                $result[$k1][$k2][]="{$lev3[$i]}_{$lev3[$i+2]}";
            }else{
                if($i%2==0){  // if index is even
                    $result[$k1][$k2][]=$lev3[$i]; // store the single value
                }
                break;  // stop the loop when no future pairing can be done
            }
        }
    }
}
var_export($result);

Output:

array (
  0 => 
  array (
    0 => 
    array (
      0 => 'A_C',
      1 => 'B_H',
      2 => 'C',
    ),
    1 => 
    array (
      0 => 'A_G',
      1 => 'D_H',
      2 => 'G_L',
    ),
    2 => 
    array (
      0 => 'D_J',
      1 => 'Z_K',
      2 => 'J_O',
      3 => 'K_X',
      4 => 'O',
    ),
  ),
  1 => 
  array (
    2 => 
    array (
      0 => 'F_W',
      1 => 'Y_H',
      2 => 'W_L',
    ),
  ),
  2 => 
  array (
    0 => 
    array (
      0 => 'O_C',
      1 => 'T_O',
      2 => 'C_X',
    ),
    1 => 
    array (
      0 => 'U_E',
      1 => 'E_D',
      2 => 'E',
    ),
  ),
)

1 Comment

If this is not your desired output, please leave me a comment. As others have mentioned, your question isn't terribly clear. Even if you are not seeking support with your question anymore, please consider improving your question so that this page can be used as a resource for future readers and a duplicate link if/when someone asks a similar question.

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.