php如何从php中的字符串中删除最后一个字符 答案调试修复原始代码

问题描述

我试图从字符串中去除最后一个 ,,但没有成功。 我需要一个这样的字符串:2,3,4 但是当试图去除最后一个 , 时,我得到了输出234 而不是 2,4

$alldays = array('2','3','4');

foreach($alldays as $day) {
    $string = $day.',';
    $string_without_last_comma = substr($string,-1);
    echo $string; // output: 2,4,echo $string_without_last_comma; // output: 234 ( should be 2,4)

}

我怎样才能做到这一点?

解决方法

答案

使用implode()

t3

Try it online!

调试

让我们来看看代码

<?php
$alldays = array('2','3','4');
$string = implode(',',$alldays);
echo $string;

所以循环确实显示了所有这些值,但它们不会相互添加,每次循环迭代只显示一次。

回顾;

  1. 由于您在执行 <?php // Define alldays $alldays = array('2','4'); // For each day foreach($alldays as $day) { // Create(=) a string,add $day and a comma $string = $day.','; // Remove the last char from $string and save ('NOT ADD') in $string_without_last_comma $string_without_last_comma = substr($string,-1); // Show string echo $string; // Show string with last char echo $string_without_last_comma; } // String here is the last char? echo $string; ,因此您将覆盖 $string = $day.','; 每个循环
  2. $string 也一样;你没有附加任何东西,只是覆盖
  3. $string_without_last_comma 会给出想要的结果

修复原始代码

注意:纯粹出于学习目的,我仍然推荐implode()

如果不使用 implode(),我的猜测是您正在尝试做这样的事情;

implode()

我们来了

  1. 创建一个空字符串
  2. 遍历所有的日子
  3. Add (.=) 天到 <?php // Define alldays $alldays = array('2','4'); // Create empty string $string = ''; // For each day foreach($alldays as $day) { // Add(.=) $day and a comma $string .= $day . ','; // Keep doing this logic for all the $day's in $alldays } // Now $string contains 2,3,4,// So here we can create $string_without_last_comma by removing the last char $string_without_last_comma = substr($string,-1); // Show result echo $string_without_last_comma; 并添加逗号
  4. 循环结束后,我们可以去掉最后一个逗号
  5. 显示结果

Try it online!