说来惭愧,以前在去掉数组的空值是都是强写foreach或者while的,利用这两个语法结构来删除数组中的空元素,简单代码如下:
<?php foreach($arr as $k=>$v){ if(!$v) unset($arr[$k]); }
事实证明如果数组过大的情况下这样处理的效率并不高。因为foreach是将当前操作的数组进行copy,每操作一下foreach,都是copy了一个变量,页面里面如果有太多的foreach,会是一个很大的消耗。
在网上闲逛的时候,看到人有提示用array_filter,于是打开手册看了一下,发现自己一直就守着个宝山却不知道如何使用。
array_filter函数的功能是利用回调函数来对数组进行过滤,如果没有回调函数,那么默认就是删除数组中值为false的项目。如下示例:
<?php $entry = array( 0 => 'foo', 1 => false, 2 => -1, 3 => NULL, 4 => '' ); print_r(array_filter($entry));
输出值为:
Array
(
[0] => foo
[2] => -1
)
建议:PHP里面最重要的两章应该就是数组操作和字符串操作,这两章里面的函数都必须要熟练,其他的就等用的时候再查吧。
您可能感兴趣的文章
- 如何删除PHP数组中的元素(unset,array_splice)?
- php清除数组中的空值元素
- php在数组中查找某个值是否存在(in_array(),array_search(),array_key_exists())
- php如何删除数组的第一个元素和最后一个元素
- PHP合并数组+与array_merge的区别
- php压入元素到数组头部(array_unshift的用法)
- php获取数组的最后一个元素
- 二维数组去除重复值和array_unique函数

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

Atom editor mac version download
The most popular open source editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment