简体   繁体   中英

remove last character from a string inside a loop in php

i am trying to check whether VIN number is valid or not using PHP. I am using for loop as shown below

 $base='**********';
foreach ($params as $key => $value) {
    $query_string .= "$key=" . urlencode($value) . "&";
    }
$url = "$base?$query_string";

in this iam getting & as last charecter like below

&reportType=3&

i tried to remove this using below code but its not working

substr($query_string, 0, -1);
 mb_substr($query_string, 0, -1);

Help me for remove last charecter

我认为您需要将结果分配回您的变量。

$query_string = substr($query_string, 0, -1);

You can use rtrim

$trimmed = rtrim($query_string, "&")

will remove any & from the end.

Your code works too, but you need to assign it to a variable since it returns a new string. Same with rtrim, by the way.

$base='index.php';
$params = array("key1"=>1,"key2"=>2,"key3"=>3,"key4"=>4);
$size = count($params);
$count = 1;
foreach ($params as $key => $value) {
    $query_string .= "$key=" . urlencode($value);
    if($count < $size){
      $query_string .= "&";
    }
    $count++;
    }
$url = "$base?$query_string";
echo $url;

//Result: index.php?key1=1&key2=2&key3=3&key4=4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM