Ignore last data explode is taking? PHP

心不动则不痛 提交于 2019-12-11 10:30:10

问题


let's say my code is.

<?php
$var = "1,2,3,4,5,6,";
$var_explode = explode(',', $var);
foreach ($var_explode as $number)
{
echo "$number test";
}
?>

And when it echos, it goes like, 1 test, 2 test, 3 test, 4 test, 5 test, 6 test, test. The last one is un-needed, I know its caused because I have a comma after the 6 in my variable, but I need that comma there, not going to remove it. Thanks!


回答1:


You can use trim($var, ",") to remove the last comma when passing the string to the explode.

$var_explode = explode(',', trim($var, ","));



回答2:


 <?php

$var = "1,2,3,4,5,6,";
$var_explode = explode(',', $var);
array_pop($var_explode); // removes last  
foreach ($var_explode as $number)
{
echo "$number test";
}
?>


来源:https://stackoverflow.com/questions/20274884/ignore-last-data-explode-is-taking-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!