我有一根绳子
$Community = "1,2,3,4,";
$ExplodeCommunity = explode(',',$Community);//Split
print_r($ExplodeCommunity);这给
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => ) 现在我要删除数组中的最后一个元素。我和array_pop一起试过
$RemovedLaste = array_pop($ExplodeCommunity);
print_r($RemovedLaste);但什么都没有印出来。如何不使用array_pop从数组中删除最后一个元素
发布于 2017-09-08 11:38:02
function remove_last($Community) {
$ExplodeCommunity = explode(',',$Community);
$remove_empty = array_values(array_filter($ExplodeCommunity));
$last_value_in_array = end($remove_empty);
$lengh = sizeof($remove_empty) -1 ;
unset($remove_empty[$lengh]);
return $remove_empty;
}
$Community = "1,2,3,4,";
print_r(remove_last($Community));
Output : Array ( [0] => 1 [1] => 2 [2] => 3 )发布于 2017-09-08 11:15:45
array_pop使用引用,因此它将影响原始数组.试试这个..。
$x=array_pop($ExplodeCommunity);
print_r($ExplodeCommunity);
var_dump($x);看看你得到了什么,顺便说一句,你想打印空值?
发布于 2017-09-08 11:46:50
问题发现
问题是当您使用下面提供的代码使用,时,字符串'1,2,3,4,'中的最后一个逗号explode:
$Community = "1,2,3,4,";
//^ The value after this is an empty string ''
$ExplodeCommunity = explode(',',$Community); 这导致$ExplodeCommunity本质上是这样的,其中最后一个条目是一个空字符串:
$ExplodeCommunity = [1,2,3,4,''] 这就是为什么在Array中有5个条目的原因。
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => )
^ This is an empty string函数array_pop返回该Array中最后一个条目的值,在本例中为空字符串''。
$RemovedLaste = array_pop($ExplodeCommunity);
print_r($RemovedLaste); // This prints an empty string ''$ExplodeCommunity的值是:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4) $Community解决方案1:保持值不变:
如果您在array_pop上执行了两次$ExplodeCommunity操作,您将得到4:
$Community = "1,2,3,4,";
//^ The value after this is an empty string ''
$ExplodeCommunity = explode(',',$Community);
$RemovedLaste = array_pop($ExplodeCommunity);
print_r($RemovedLaste); // This prints an empty string ''
$RemovedLaste = array_pop($ExplodeCommunity);
print_r($RemovedLaste); // This prints 4$ExplodeCommunity的值是:
Array ( [0] => 1 [1] => 2 [2] => 3) rtrim解决方案2:使用删除结束逗号
您可以像下面这样使用rtrim从$Community字符串中删除结尾逗号:
$Community = rtrim("1,2,3,4,", ',');
$ExplodeCommunity = explode(',',$Community);
$RemovedLaste = array_pop($ExplodeCommunity);
print_r($RemovedLaste); // This prints 4$ExplodeCommunity的值是:
Array ( [0] => 1 [1] => 2 [2] => 3) 其他解决方案
您可以使用其他函数,如unset/array_slice,如其他答案所述。
https://stackoverflow.com/questions/46115140
复制相似问题