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

Asked

Viewed 2,967 times

3

Guys I got the following foreach:

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

He returns to me:

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

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

3 answers

2

Can match Count to obtain the last element of 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];
  • Note that it only works with numerical arrays.

2


You can use the function implode:

$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.

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 (no numerical index).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.