search
HomeBackend DevelopmentPHP ProblemHow to remove blank elements from php array

In PHP development, processing arrays is a very common operation. In practical applications, we often encounter situations where arrays contain blank elements. If these blank elements are not handled, the normal operation of the program may be affected. Therefore, this article will show you how to remove blank elements from an array using PHP.

1. What is a blank element

In PHP, we can create an array in the following way:

$arr = array('foo', '', 'bar');

The above code creates an array containing 3 elements, where The first element is 'foo', the second element is the empty string, and the third element is 'bar'. In actual development, there are many cases of such blank elements. For example, blank data may exist in form data submitted by users, or blank data may also appear in database query operations.

2. Use the array_filter() function to remove blank elements

PHP has many useful array functions built-in, including the array_filter() function. The array_filter() function is used to filter elements in an array according to specified conditions and return a new array. Typically, we use the callback function of the array_filter() function to filter array elements to remove blank elements.

The following is a sample code that uses the array_filter() function to remove blank elements in an array:

$arr = array('foo', '', 'bar');

// 定义回调函数
function filter_empty($var) {
    return trim($var) != '';
}

// 使用 array_filter() 函数去除空白元素
$arr = array_filter($arr, 'filter_empty');

// 输出新数组
print_r($arr);

Run the above code, the output result is:

Array
(
    [0] => foo
    [2] => bar
)

As can be seen from the above code , use the array_filter() function to remove blank elements from the original array, and return a new array containing only non-empty elements.

In the above example code, we use a function named filter_empty as the callback function. This function uses the trim() function to remove spaces on both sides of the string, and then determines whether the string is an empty string. If it is not an empty string, it returns true, indicating that the element needs to be retained; otherwise, it returns false, indicating that the element needs to be filtered out.

3. Use foreach() to operate the array

In addition to using the array_filter() function, you can also use foreach() to loop through the array, and then use the unset() function to delete blank elements. The following is a sample code that uses foreach() loop to remove blank elements in the array:

$arr = array('foo', '', 'bar');

foreach ($arr as $i => $value) {
    if (trim($value) == '') {
        unset($arr[$i]);
    }
}

// 重新建立索引
$arr = array_values($arr);

// 输出新数组
print_r($arr);

Run the above code, the output result is:

Array
(
    [0] => foo
    [1] => bar
)

In the above code, we use foreach() to loop through each element in the array. If the element is a blank element, that is, it is an empty string after calling the trim() function to remove the spaces on both sides, then use the unset() function to delete the element. Finally, we re-index the array using the array_values() function, resulting in a new array that does not contain blank elements.

4. Use the array_reduce() function to remove blank elements

In addition to the above two methods, you can also use the array_reduce() function to remove blank elements in the array. The array_reduce() function is used to iterate each element of the array, calculate all elements through the callback function, and return a single value.

The following is a sample code that uses the array_reduce() function to remove blank elements in an array:

$arr = array('foo', '', 'bar');

// 定义回调函数
function reduce_empty($carry, $item) {
    if (trim($item) != '') {
        $carry[] = $item;
    }
    return $carry;
}

// 使用 array_reduce() 函数去除空白元素
$arr = array_reduce($arr, 'reduce_empty', array());

// 输出新数组
print_r($arr);

Run the above code, the output result is:

Array
(
    [0] => foo
    [1] => bar
)

In the above code, we A function called reduce_empty is defined that iterates over each element of the array. If the element is not a blank element, the element is added to a new array and the new array is returned. Finally, use the array_reduce() function to remove blank elements from the original array and return the new array.

5. Summary

This article introduces three methods of using PHP to remove blank elements in an array: using the array_filter() function, using the foreach() loop and using the array_reduce() function. Although these methods are different, they can all effectively remove blank elements in the array, thereby avoiding affecting the normal operation of the program. In actual development, we can choose the appropriate method to operate according to the actual situation.

The above is the detailed content of How to remove blank elements from php array. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.