微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。