troubleshooting Question

Array rTrim or not?

Avatar of Michel Plungjan
Michel PlungjanFlag for Denmark asked on
PHP
30 Comments2 Solutions506 ViewsLast Modified:
Having implemented an rTrim on my array I still get commas at the end of my csv

What am I missing and is it by the way an elegant way to not have to test each item for existence or should I change my array creation?
for ($j=0;$j<count($object);$j++) {
    $line = array();
    $line[] = $object[$j]->{"item 1"};
    $line[] = $object[$j]->{"item 2"};
    $line[] = $object[$j]->{"item 3"};
    $line[] = $object[$j]->{"item 4"};
    while ("" === end($line)) { // pop off empty stuff before writing
      array_pop($line);
    }    
    fputcsv($out,$line);
  }
}  

I was thinking to make another array:
$fields = ["item 1","item 2","item 3","item 4"];
for ($i=0;$i<count($object);$i++) {
    $line = [];
   for ($j=0;$j<count($fields);$j++) {
     if ($object[$i] has a value in $fields[$j]) {
       $line[] = $object[$i]->$fields[$j];
      }    
    }
    fputcsv($out,$line);
  }
}  
but I do not know how to

a) test $object[$i] has a value in $fields[$j]
b) use the $fields[j] instead of ->{"item X"};

Thanks for your thoughts
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 2 Answers and 30 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 2 Answers and 30 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros