Search code examples
phpmultidimensional-arrayforeachimplode

foreach loop to print key value pairs while imploding the nested arrays


I'm trying to print all of the key value pairs we are getting from a form with a foreach loop. The problem is for the $values that are nested arrays, it is only printing array.

I would like this value to be flattened while maintaining the key. I've been trying an implode(', ', $value); in the loop. Is there a way to do this?

My current code is

foreach($cleanedArray as $key => $value) {
    echo "$key: $value <br>";
}  

Which outputs the following:

company_name: asldjfklka 
contact_name: lkdasjf;l 
contact_phone: 39085034985 
contact_email: [email protected] 

Notice: Array to string conversion in /Applications/MAMP/htdocs/certification-questionnaire-4.0/php/formshow.php on line 105
company_type: Array 
campaign: no 

I've been trying an if statement within the foreach loop without luck.

    foreach($cleanedArray as $key => $value) {
  if (is_array($value)){
     implode(', ', $value);
  } 
    echo "$key: $value <br>";
}  

The output that I'm looking for is this:

  company_name: asldjfklka 
  contact_name: lkdasjf;l 
  contact_phone: 39085034985 
  contact_email: [email protected] 
  company_type: retail, ecommerce, brickmorter
  campaign: no 

any ideas? thanks in advance.


Solution

  • In case of array you need to assign the result of implode to a variable:

    foreach($cleanedArray as $key => $value) {
      if (is_array($value)){
         // here
         $value = implode(', ', $value);
      } 
      echo "$key: $value <br>";
    }