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删除数组中的空元素
总结
以上是生活随笔为你收集整理的php删除数组中的空元素_PHP | 从数组中删除所有出现的元素的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: Java BigInteger类| bi
- 下一篇: PHP | 计算字符串中的单词总数