Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 转换为数组后,删除不起作用的字符串上的元素_Php - Fatal编程技术网

Php 转换为数组后,删除不起作用的字符串上的元素

Php 转换为数组后,删除不起作用的字符串上的元素,php,Php,下面的代码解释了如何使用unset函数删除元素, 我使用了一个字符串并将该字符串转换为数组, 现在尝试删除第一个和最后一个元素。 但是这些元素不会被删除。 我会很感激你的帮助 <?php $string="Cupid"; //orginal string $stringmod= str_split($string); //converted the string to an array $length= count($stringmod); //length of

下面的代码解释了如何使用unset函数删除元素, 我使用了一个字符串并将该字符串转换为数组, 现在尝试删除第一个和最后一个元素。 但是这些元素不会被删除。 我会很感激你的帮助

<?php
$string="Cupid";  //orginal string
$stringmod= str_split($string);  //converted the string to an array
$length= count($stringmod); //length of the string
for($i=0; $i<$length; $i++) 
{

    if($i == 0 || $i == $length-1) //condition to be executed
    {
        
        unset($stringmod[$i]); //delete elements
    
    }
    
}
print_r($stringmod);
?>

数组\u shift
将从数组中删除第一个元素,重新索引数字键

array\u pop
将删除最后一个

$string="Cupid";  //orginal string
$stringmod= str_split($string); 

array_shift($stringmod);
array_pop($stringmod);

print_r($stringmod);

如果您想通过循环执行此操作,如所示,您基本上已经完成了,您只需要在
for
循环中正确引用测试计数器。

关于您的代码,您在循环中缺少$BEER length

尽管如此:不需要在数组中循环-您可以直接寻址元素。以下工作将起作用:

<?php
   $string="Cupid";
   $stringmod= str_split($string);
   unset($stringmod[count($stringmod)-1]);
   unset($stringmod[0]);
   print_r($stringmod);
?>

函数array\u pop和array\u shift也将执行相同的操作(从数组中删除最后/第一个元素)。如果您想在代码的后面再次执行此操作,它们会更好(PHP使用关联数组,因此$stringmod[0]只是开始时的第一个元素-当您删除它时,不再有$stringmod[0],因此执行unset($stringmod[0])两次不会删除两个“第一”元素,而只删除一个)。因此,在这种情况下,最好的答案可能是:

<?php
   $string="Cupid";
   $stringmod= str_split($string);
   array_pop($stringmod);
   array_shift($stringmod);
   print_r($stringmod);
?>


另外,根据Andrew在我回答下面的评论,您还可以使用array_values()函数重新排序,或者使用array_splice()删除元素(这也将重新排序)。就我个人而言,我不喜欢使用它们,因为它们占用资源,如果可能的话,我也不依赖于数组具有魔法数字的排序索引:)

length
更改为
$length
。。。并将错误报告改为ON,而不是遍历数组,您可能会发现这个答案很有帮助:长度是一个类型错误,很抱歉,要绕过
unset
扰乱索引的问题,您可以使用
array\u value
对键进行重新排序。谢谢Andrew。使用array_splice也是删除元素的一个选项-它还可以重新排序,因此我们可以通过array_splice删除两次第一个元素($stringmod,0,1)。但这些功能需要资源。就我个人而言,我不喜欢使用它们。