PHP去除数组中的空值元素(array_filter)
说来惭愧,以前在去掉数组的空值是都是强写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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

To work on file upload we are going to use the form helper. Here, is an example for file upload.

Validator can be created by adding the following two lines in the controller.

Logging in CakePHP is a very easy task. You just have to use one function. You can log errors, exceptions, user activities, action taken by users, for any background process like cronjob. Logging data in CakePHP is easy. The log() function is provide

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP is an open source MVC framework. It makes developing, deploying and maintaining applications much easier. CakePHP has a number of libraries to reduce the overload of most common tasks.
