In a given array containing elements, how to delete empty elements in the array, such as empty strings, NULL elements, etc.? The following article will show you how to delete empty elements in an array. I hope it will be helpful to you.
Method 1: Use empty() function and unset() function
empty() function Used to check if an element is empty.
The unset() function is used to unset the specified variable, and its behavior depends on different things.
Example:
<?php header("content-type:text/html;charset=utf-8"); // 声明和初始化数组 $array = array("php", 11, '', null, 12, "javascript", 2018, false, "mysql"); echo ("<br>"); // 显示原数组元素 echo ("原数组元素:<br>"); foreach($array as $key => $value) echo ("'".$array[$key] . "' "); echo ("<br><br><br>"); // 循环查找空元素并取消设置空元素 foreach($array as $key => $value) if(empty($value)) unset($array[$key]); // 显示新数组元素 echo ("新数组元素:<br>"); foreach($array as $key => $value) echo ("'".$array[$key] . "' "); ?>
Output:
##Method 2: Use array_filter() function
The array_filter() function, also known as the callback function, is used to filter the elements of an array using a user-defined function. It iterates over each value in the array, passing them to a user-defined function or callback function. When the array_filter() function is used to declare a callback function, it will delete false values, but if the callback function is not specified, all values in the array that are equal to FALSE, such as empty strings or NULL values, will be deleted . Example:<?php header("content-type:text/html;charset=utf-8"); // 声明和初始化数组 $array = array("php", 11, '', null, 12, "javascript", 2018, false, "mysql"); echo ("<br>"); // 显示原数组元素 echo ("原数组元素:<br>"); foreach($array as $key => $value) echo ("'".$array[$key] . "' "); echo ("<br>"); // 使用array_filter()函数从数组中移除空元素 $filtered_array = array_filter($array); // 显示新数组元素 echo ("新数组元素:"); //foreach($array as $key => $value) // echo ("'".$array[$key] . "' "); var_dump($filtered_array); ?>
The above is the detailed content of How to remove empty elements from array in PHP? (code example). For more information, please follow other related articles on the PHP Chinese website!