phpormiteratorforeachcountable

Last item in iteration with PHP


I want to separate iteration results by comma, but it's not an array. I want to do it in views, so code shouldn't be long.

<?php foreach ($roles as $role): ?>
    <?php echo $role->title; ?>
<?php endforeach; ?>

Result object implements Countable, Iterator, SeekableIterator, ArrayAccess.


Solution

  • Not certain I understand what your asking (your code basically seems to do what you say?) the only thing i see missing is separate by comma.

    <?php
    $first=true;
    foreach ($roles as $role) {
      if (!$first) echo ",";
      $first=false;
      echo $role->title;
    }
    ?>
    

    Or if caching is ok (string length isn't too long):

    <?php
    $output="";
    foreach ($roles as $role) {
      $output.=$role->title.",";
    }
    echo substr($output,0,-1);//Trim last comma
    ?>