php unset函数_PHP | 使用unset()函数从数组中删除元素

php unset函数

Given an array and we have to remove an element from the array.

给定一个数组,我们必须从数组中删除一个元素。

unset()函数 (unset() function)

To remove an element from an array, we can use a PHP library unset() function, it accepts the index and removes the element exists on the specified index.

要从数组中删除元素 ,我们可以使用PHP库unset()函数 ,该函数接受索引并删除指定索引上存在的元素。

We are also using another function var_dump() – which dumps the variable details i.e. here, it will print the array variable.

我们还使用了另一个函数var_dump() -转储变量的详细信息,即在这里,它将打印数组变量。

PHP code to remove an element from an array

PHP代码从数组中删除元素

<?php
//PHP code to remove an element from an array 

//declaring an array of strings
$array = array('the','quick','brown','fox');

//printing the array variable
var_dump($array);

//removing element from 1st index
unset ($array[1]);

//again, printing the array variable
var_dump($array);

//assigning the array after removing its element
//from 1st index to the new array
$array_new=array_values($array);

//printing the new array variable
var_dump($array_new);
?>

Output

输出量

array(4) {
  [0]=>
  string(3) "the"
  [1]=>
  string(5) "quick"  
  [2]=>
  string(5) "brown"  
  [3]=>
  string(3) "fox" 
}
array(3) {
  [0]=>
  string(3) "the" 
  [2]=>
  string(5) "brown"  
  [3]=>
  string(3) "fox" 
}
array(3) {
  [0]=>
  string(3) "the" 
  [1]=>
  string(5) "brown"  
  [2]=>
  string(3) "fox" 
}

Explanation:

说明:

Here, We've created an array ($array) and then used the PHP unset() method to remove index 1 (which is the 2nd value since array starts from 0). Once that's removed, we print the array using var_dump but there is a problem that the indexes haven't updated. So, we create $array_new by using array_values() method on the existing $array.

在这里,我们创建了一个数组( $ array ),然后使用PHP unset()方法删除了索引1(这是第二个值,因为array从0开始)。 删除后,我们使用var_dump打印数组,但是存在索引尚未更新的问题。 因此,我们通过在现有$ array上使用array_values()方法创建$ array_new 。

翻译自: https://www.includehelp.com/php/delete-an-element-from-an-array-using-unset-function.aspx

php unset函数

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值