Last item in iteration with PHP

208 Views Asked by At

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.

2

There are 2 best solutions below

0
On BEST ANSWER

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
?>
0
On

If your $roles variable is an object, write a method that returns an array of property values. Something like:

class Roles implements Countable, Iterator, SeekableIterator, ArrayAccess {

  //main body of the class here

  public function prop_as_array($prop){
    if(!property_exists('Role', $prop)) throw new Exception("Invalid property");
    $arr=array();
    if(count($this)==0) return $arr
    foreach($this as $role){
      $arr[]=$role->$prop;
    }
    return $arr;
  }

}

//on output page
$roles=new Roles;
echo implode(',', $roles->prop_as_array('title'));