-1

I have this array:

  $bonusarraymain = array(

     array( "bonus1"=> "Testitem" , 
         ),
     array( "bonus2"=> "" , 
         ),
     array( "bonus3"=> "444" , 
         ),
     array( "bonus4"=> "" , 
         )
    );

I want to echo out the values which aren´t empty. The values should also be separated with a comma between each other. There shouldn´t be a comma after the last value.

This is how I output the values, but how can I separate them with commas?

          foreach ($bonusarraymain as $bonus) {
                echo $bonus['bonus1'];
                echo $bonus['bonus2']['0'];
                echo $bonus['bonus2']['1'];
                echo $bonus['bonus3'];
                echo $bonus['bonus4'];
            
       }
Berstos
  • 179
  • 10
  • Then I have a comma after the last value. I need some check to see which value is the last so it doesn´t set a comma after this value. – Berstos Mar 27 '21 at 01:41

3 Answers3

1

Create a new array with those values and use implode() to insert the comma

foreach ($bonusarraymain as $bonus) {
      $items = array($bonus['bonus1'], 
                     $bonus['bonus2']['0'],
                     $bonus['bonus2']['1'],
                     $bonus['bonus3'],
                     $bonus['bonus4']);
      echo implode(',' , $items);            
}

Will leave it to you to figure out how to filter out the empty ones. Hint: array_filter()

charlietfl
  • 170,828
  • 13
  • 121
  • 150
1

Also could use array_reduce to populate a new filtered array, then simply join the resulting array with implode.

<?php
$bonusarraymain = [
    [ "bonus1"=> "Testitem" ], 
    [ "bonus2"=> "" ],
    [ "bonus3"=> "444" ],
    [ "bonus4"=> "" ]
];

echo implode(', ', array_reduce($bonusarraymain, function($acc, $cur) {
    $cur = array_values($cur);
    if (isset($cur[0]) && !empty($cur[0])) $acc[] = $cur[0];
    return $acc;
}, []));

Result: Testitem, 444

Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
  • `isset() && !empty()` is an antipattern that should not exist in any code for any reason. https://stackoverflow.com/a/4559976/2943403 – mickmackusa Apr 29 '23 at 21:47
0

Difficult to see what you're trying to do. Is $test supposed to be $bonus?

Update:

Use a for loop and check the index. Something like this:

for ($bonusId = 0; $bonusId < count($bonusarraymain); $bonusId++) {
  echo $bonus['bonus1'] . ",";
  echo $bonus['bonus2']['0'] . ",";
  echo $bonus['bonus2']['1'] . ",";
  echo $bonus['bonus3'] . ",";
  echo $bonus['bonus4'];

  if ($bonusId < count($bonusarraymain)-1) {
    echo ","
  }        
}
JohnFF
  • 723
  • 5
  • 20