-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'];
            
       }
1
  • 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. Commented Mar 27, 2021 at 1:41

3 Answers 3

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()

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

isset() && !empty() is an antipattern that should not exist in any code for any reason. stackoverflow.com/a/4559976/2943403
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 ","
  }        
}

2 Comments

Yes, I changed it. But how can I get commas between the values execpt after the last one?
Updated my response to contain your answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.