user1320330
user1320330

Reputation:

how to remove last char from string

It might be a simple task. But I am new to PHP.

I am creating a string of values getting from database for a specific purpose.

How to remove last char from string.

$str='';
foreach($dataarray as $value)
{
   $str.=$value."##";
 }

it gives me string like ABC##DEF##GHI##

I have to remove last 2 chars ##

EDIT:

have shown here sample code . actull y array is 2D. so cant use implode()

Upvotes: 4

Views: 12165

Answers (9)

biziclop
biziclop

Reputation: 14616

If the implode method isn't appropriate, then after your foreach loop, you can try one of these functions:

http://www.php.net/manual/en/function.rtrim.php

$str = rtrim($str,'#');

http://php.net/manual/en/function.substr.php

$str = substr($str,-2);

If you have a 2D array, you could still use the implode func like this:

$a = array();
foreach( $foo as $bar )
  foreach( $bar as $part )
    $a[] = $part;
$str = implode('##',$a);

Upvotes: 7

rsc
rsc

Reputation: 10678

Use substr:

$str = substr($str,0, -2);

http://php.net/manual/en/function.substr.php

Upvotes: 1

Romancha KC
Romancha KC

Reputation: 1527

<?php
$str = "1,2,3,4,5,";
echo chop($str,",");
?>

It will remove last comma (,) from the string $str

Upvotes: 1

Dion
Dion

Reputation: 3345

Maybe

$str='';
$first = true;
foreach($dataarray as $value) {
     if(!$first) {
          $str .= "##";
     }
     else {
          $first = false;
     }
     $str .= $value;
 }

Upvotes: 0

still_learning
still_learning

Reputation: 46

http://php.net/manual/en/function.substr-replace.php

$newstr = substr_replace($longstr ,"",-2);

This will create $newstr by taking $longstr and removing the last tow characters.

Upvotes: 0

Aaron Webb
Aaron Webb

Reputation: 67

There's a few ways to go about it but:

$str = rtrim($str, "#");

Upvotes: 0

Mortana
Mortana

Reputation: 1442

You could use PHP's function implode

$str = implode("##", $dataarray);

Upvotes: 1

user319198
user319198

Reputation:

You can use Implode() for making such string instead of making it manually

implode("##",$dataarray);

BTW for removing last char you can do like below:

substr($str,0,(strlen($str)-2));

Upvotes: 0

Nanne
Nanne

Reputation: 64429

You might be better of just to use implode instead of this loop?

implode ( "##" , $dataarray  );

Upvotes: 6

Related Questions