Home  >  Article  >  Backend Development  >  How to remove blank spaces from array values ​​in php

How to remove blank spaces from array values ​​in php

藏色散人
藏色散人Original
2022-12-26 09:52:244040browse

php method to remove empty elements from array values: 1. Use "array_filter(array)" to delete empty elements in the array; 2. Use foreach or while syntax structures to delete empty elements in the array. The syntax is as follows: foreach( $arr as $k=>$v){if( !$v )unset( $arr[$k] );}}".

How to remove blank spaces from array values ​​in php

The operating environment of this tutorial: Windows 10 system, PHP version 8.1, DELL G3 computer

How to remove blank array values ​​in php?

php Array removes null values ​​array_filter() method

  • ##array_filter()

Calling method: array_filter(array) Parameter description: array is the object of the operation, we will delete the empty elements

Instance:

Result:

Array (
[a] => abc
[b] => bcd
[c] => cde
[d] => def
)

  • foreach or while, use these two syntax structures to delete empty elements in the array. The simple code is as follows:

  • <?php
    foreach( $arr as $k=>$v){
    if( !$v )
    unset( $arr[$k] );
    }
    ?>
And I feel pretty good about myself, but it’s not very efficient. I’ve tried it before, first converting $arr to an object, and then using the characteristics of the object to delete it, because: foreach copies the current array of operations, and every operation Each foreach copy copies a variable. If there are too many foreachs on the page, it will be a huge waste.

Recommended learning: "

PHP Video Tutorial"

The above is the detailed content of How to remove blank spaces from array values ​​in php. 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