Home  >  Article  >  Backend Development  >  PHP filtering empty array method and filtering empty elements in the array_PHP tutorial

PHP filtering empty array method and filtering empty elements in the array_PHP tutorial

WBOY
WBOYOriginal
2016-07-20 11:07:34771browse

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
*/


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/444942.htmlTechArticlephp Method of filtering empty arrays and filtering empty elements in the array. I have given three examples below. , one is for, foreach, array_filter to process, see the example php tutorial below...
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