How to remove the last character from the last value of an array

3

I have the following foreach:

$items = "";
foreach ($_POST['termos'] as $item) {
  if(isset($item)){
          $items = $items . $item . '+';
  }
}

It returns me:

Array ( 
[0] => 1-valor+ 
[1] => 2-valor+ 
[2] => 3-valor+
 )

Question: How to ALWAYS remove the last character from the last value of this array, in this case the + ?

    
asked by anonymous 02.03.2015 / 02:05

3 answers

2

You can use the implode function:

$items = [];
foreach ($_POST['termos'] as $item) {
  if(isset($item)){
      array_push($items, $item);
  }
}

$string = implode('+', $items);
echo $string; // residencial+mecanico+display+led

Demonstration in Ideone .

    
02.03.2015 / 02:13
2

You can combine count to get the last element in the array and subtstr to remove the last character from the array:

<?php
$arr = array('1-valor+','2-valor+','3-valor+');
$ultimo = count($arr) - 1; //3 elementos
$arr[$ultimo] = substr($arr[$ultimo],0, -1); //remove o último caracter

echo $arr[$ultimo];
    
02.03.2015 / 02:12
2

Using the functions substr and functions end and key

<?php 

end($items);
$key = key($items);

$items[$key] = substr($items[$key], 0, -1);

In this case it works with associative arrays (without numeric index).

    
02.03.2015 / 02:18