php删除数组中的空元素_PHP | 从数组中删除所有出现的元素

php删除数组中的空元素

Given an array and we have to remove all occurrences of an element from it.

给定一个数组,我们必须从中删除所有出现的元素。

array_diff()函数 (array_diff() function)

To remove all occurrences of an element or multiple elements from an array – we can use array_diff() function, we can simply create an array with one or more elements to be deleted from the array and pass the array with deleted element(s) to the array_diff() as a second parameter, first parameter will be the source array, array_diff() function returns the elements of source array which do not exist in the second array (array with the elements to be deleted).

要从数组中删除所有出现的一个元素或多个元素 –我们可以使用array_diff()函数 ,我们可以简单地创建一个包含一个或多个要从该数组中删除的元素的数组,并将带有已删除元素的数组传递给array_diff()作为第二个参数,第一个参数将是源数组, array_diff()函数返回第二个数组中不存在的源数组元素(带有要删除的元素的数组)。

PHP code to remove all occurrences of an element from an array

PHP代码从数组中删除所有出现的元素

<?php
//array with the string elements
$array = array('the','quick','brown','fox','quick','lazy','dog');

//array with the elements to be delete 
$array_del = array('quick');

//creating a new array without 'quick' element
$array1 = array_values(array_diff($array,$array_del));
//printing the $array1 variable
var_dump($array1);

//now we are removing 'the' and 'dog'
//array with the elements to be delete 
$array_del = array('the', 'dog');

//creating a new array without 'the' and 'dog' elements
$array2 = array_values(array_diff($array,$array_del));
//printing the $array2 variable
var_dump($array2);
?>

Output

输出量

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

Explanation:

说明:

We use the array_diff() method to calculate the difference between two arrays which essentially eliminates all the occurrences of an element from $array, if they appear in $array_del. In the given example, we delete all the occurrences of the words quick and brown from $array using this method.

我们使用array_diff()方法来计算两个数组之间的差,如果它们出现在$ array_del中 ,则基本上消除了$ array中所有元素的出现。 在给定的示例中,我们使用此方法从$ array中删除了出现的所有quick和brown单词。

翻译自: https://www.includehelp.com/php/delete-all-occurrences-of-an-element-from-an-array.aspx

php删除数组中的空元素

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值