$v){if($v == " "){unset($arr[$k]);}} ". 2. Call the callback function through array_filter() to process the array elements and filter out the space elements."/> $v){if($v == " "){unset($arr[$k]);}} ". 2. Call the callback function through array_filter() to process the array elements and filter out the space elements.">

Home >Backend Development >PHP Problem >How to remove space elements in an array in php

How to remove space elements in an array in php

青灯夜游
青灯夜游Original
2022-05-23 20:11:573460browse

Two methods: 1. Traverse the array and delete space elements. The syntax "foreach($arr as $k=>$v){if($v == " "){unset($arr[ $k]);}}". 2. Call the callback function through array_filter() to process the array elements and filter out the space elements.

How to remove space elements in an array in php

The operating environment of this tutorial: windows7 system, PHP8.1 version, DELL G3 computer

php remove the array Two methods for space elements

Method 1: Traverse the array and delete space elements

<?php
$arr = [11," ",33," ",44," ",66];
var_dump($arr);
foreach($arr as $k=>$v){
	if($v==" "){
		unset($arr[$k]);
	}
}
var_dump($arr);
?>

How to remove space elements in an array in php

Method 2: Use array_filter() to filter space elements

The array_filter() function uses a callback function to filter elements in the array.

This function passes each key value in the input array to the callback function. If the callback function returns true, the current key value in the input array is returned to the result array. Array key names remain unchanged.

Example:

<?php
function f($var){
    return($var !=" ");
}
$arr = [11," ",33,44," ",66];
var_dump($arr);
$NewArr=array_filter($arr,"f");
var_dump($NewArr);
?>

How to remove space elements in an array in php

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to remove space elements in an array 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