How to remove the last character, save the result to a variable and use the variable outside the foreach?

3

I have a code PHP like this:

foreach ($rows as $obj) :

    $all_ids = $obj->ID . ', ';

endforeach;

.. whose output is 125, 148, 157, 169, 185,

How to remove the last comma and save the rest of the output in a variable to use it outside of foreach ?

    
asked by anonymous 30.07.2015 / 01:59

3 answers

1

You can use the trim to remove the last character on the right, the second argument says which one should be the character.

Trim

<?php
   $rows = array("125", "148", "157", "169", "185");
   $all_ids = "";
   foreach ($rows as $item){
      $all_ids .= $item.", ";
   }

   echo trim(trim($all_ids),',');

Example - ideone

substr

Or with substr, which will remove space and comma.

<?php
   $rows = array("125", "148", "157", "169", "185");
   $all_ids = "";
   foreach ($rows as $item){
      $all_ids .= $item.", ";
   }

   $all_ids = substr($all_ids, -0, -2);
   echo $all_ids;

Example - ideone

array_map

From php5.3 you can use anonymous functions, which combined with array_map () removes the foreach. array_map applies a function to all elements of an array ( $row ), the anonymous function only returns the ID property of the object, then just use the implode () to convert the array to a comma-separated string, as demonstrated by Jefferson Silva.

This approach was taken from PHP - Extracting property from an array of objects

<?php
   //Monta um array igual ao da pergunta
   $valores = array("125", "148", "157", "169", "185");
   for($i=0; $i<5; $i++){
     $obj = new stdClass();
     $obj->ID = $valores[$i];
     $rows[] = $obj;
   }

   $all_ids  =  array_map(function($item){ return $item->ID; }, $rows);
   echo implode(',', $all_ids);

Example - ideone

    
30.07.2015 / 02:15
3

I usually use a simpler approach when I want to transform an array or object into a string separated by commas.

<?php
   $rows = array("125", "148", "157", "169", "185");
   echo implode(',',$rows); //125,148,157,169,185
?>
    
30.07.2015 / 14:52
2

Although the @rray response is quite simple and useful, there is also another way to achieve the desired result. Use bool to see if an item is first or not in the list.

An example:

<?php
   $rows = array("125", "148", "157", "169", "185");
   $all_ids = "";
   $first_row = true;
   foreach ($rows as $item){
      if ( $first_row ) {
       $first_row = false;
       $all_ids .= $item;
      } else {
       $all_ids .= ", ".$item;
      }
   }

This is very useful in languages that do not have a trim() function that accepts values beyond space.

    
30.07.2015 / 05:32