2

I would like to separate array values echoed from foreach loop

<?php foreach($qty as $qty2): ?> 
    <?php foreach($qty2 as $q): ?>
         <?php echo implode(",", $q); ?>
    <?php endforeach ?>
<?php endforeach ?> 

A PHP Error was encountered

Severity: Warning

Message: implode(): Invalid arguments passed

Without adding implode function, my values would normally like this

87 89 78

It looks confusing so I would like to output as

  87, 89, 78

or

  87 - 89 - 78

or

  (87)(89)(78)

The idea is to show the users that they are different values from array

The qty array

  Array ( [0] => Array ( [qty] => 24 ) [1] => Array ( [qty] => 24 ) [2] => Array ( [qty] => 24 ) )

Now I tried this

   <?php foreach($qty as $qty2): ?> 
      <?php foreach($qty2 as $q): ?>
          <?php echo $q . " , " ; ?>
       <?php endforeach ?>
   <?php endforeach ?>     

Result

  24 , 24 , 24 ,

There is always a trailing comma at the end

Any Ideas?

Danielle Rose Mabunga
  • 1,676
  • 4
  • 25
  • 48

2 Answers2

1

Don't use implode on each element, on the iteration.

Just gather all the elements first inside a container, then use implode().

<?php
$data = array();
foreach($qty as $qty2) {
    $data[] = $qty2['qty']; // gather all qty first
}
echo implode(', ', $data); // implode collected elements
?>

Or if array_column is available, you could use it too:

<?php

echo implode(', ', array_column($qty, 'qty'));

?>
Kevin
  • 41,694
  • 12
  • 53
  • 70
1

You can also use join() function to separate array values.. in join first argument is your delimiter and second is the array.

<?php 
  $qty = array(
    0 => array('qty' => 24 ), 
    1 => array('qty' => 24 ), 
    2 => array('qty' => 24 )
  );

  $arr = array();
  foreach ($qty as $q) {
    $arr[] = $q['qty'];
  }

 /// used delimiter ','
 echo join(',', $arr);
 echo "<br>";

 /// used delimiter '-'
 echo join('-', $arr);

?>

This will output

24,24,24
24-24-24
Sibiraj PR
  • 1,481
  • 1
  • 10
  • 25
Manjeet Barnala
  • 2,975
  • 1
  • 10
  • 20