Home >Backend Development >PHP Tutorial >PHP filtering empty array method and filtering empty elements in the array_PHP tutorial
PHP filtering empty array method and filtering array elements that are empty. I have given three examples below. One is for, foreach, array_filter to handle. Let’s look at the example below
PHP tutorial filtering empty array method and filtering array. Empty elements
I have given three examples below for filtering empty arrays. One is for, foreach, array_filter to handle. Let’s look at the examples below
*/
//Method 1 uses array_filter Call our custom function to filter empty values
function clear($a)
{
return $a <> "";
}$array = array("",'','','','',1,1,1,1,1);
$stt = array_filter($array , "clear");
print_r( $stt );
/*
Output result
Array
(
[5] => 1
[6 ] => 1
[7] => 1
[8] => 1
[9] => 1
)
Null values are filtered
* /
//Filter empty data 2, use loop to process
$array = array("",'','2','' ,'',1,1,1,1,1);
foreach( $array as $v =>$vc )
{
if( $vc =='' )
{
unset($array[$v]);
}
}print_
r( $array);
/*
Array
(
[2] => 2
[5] => 1
[6] => 1
[7] = > 1
[8] => 1
[9] => 1
)
*/
//Method example three, use for to instantiate
$tarray = array('','11','','www.bkjia.com','','','cn.net');
$ len = count( $tarray );
for( $i=0;$i<$len;$i++ )
{
if( $tarray[$i] == '' )
{
unset( $tarray[$i]);
}
}print_r($tarray);
/*
Filter empty The result after the array is
Array
(
[1] => 11
[3] => www.bkjia.com
[6] => cn .net
)
Note: The original tutorial on this site is reprinted with the source www.bkjia.com
*/