Home Backend Development PHP Tutorial PHP array filter function array_filter and array_unique_PHP tutorial

PHP array filter function array_filter and array_unique_PHP tutorial

Jul 13, 2016 am 10:44 AM
array filter php unique and introduce function exist Commonly used array Compare filter

In PHP, I will introduce to you two commonly used array filtering functions, array_filter and array_unique. One is to filter array empty values, and the other is to filter array duplicate values. Let’s take a look together now.

Grammar
array_filter(array,function)
Parameter Description
array Required. Specifies the input array.
function The name of the custom function, when it is empty, all elements whose value is false are filtered out

The code is as follows Copy code
 代码如下 复制代码


function odd($var) {
return($var & 1);
}

function even($var) {
return(!($var & 1));
}

$array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
$array2 = array(6, 7, 8, 9, 10, 11, 12);
 
echo "Odd :n";
print_r(array_filter($array1, "odd"));
echo "Even:n";
print_r(array_filter($array2, "even"));
/*
 
Odd :
Array
(
   
[a] => 1
   
[c] => 3
   
[e] => 5
)
Even:
Array
(
   
[0] => 6
   
[2] => 8
   
[4] => 10
   
[6] => 12
)
*/

function odd($var) { Return($var & 1);

}

function even($var) {
代码如下 复制代码

$arrF = array();
$arrS = array();
$intTotal = 100;
$intRand = 10;
for($i=0; $i < $intTotal; $i++)
{
$arrF[] = rand(1, $intRand);
$arrS[] = rand(1, $intRand);
}
$arrT = array_merge($arrF, $arrS);
$arrRF = array();
$intStart = time();
foreach($arrT as $v)
{
if(in_array($v, $arrRF))
{
continue;
}
else
{
$arrRF[] = $v;
}
}
$intEnd = time();
$intTime = $intEnd-$intStart;
echo "With Continue,Spend time:$intTime
";
$intStart1 = time();
$arrRS = array_unique($arrT);
$intEnd2 = time();
$intTime2 = $intEnd2-$intStart1;
echo "With array_unique function,Spend time:($intTime2)";
echo "

";<br>
print_r($arrT);<br>
print_r($arrRF);<br>
print_r($arrRS);<br>
echo "
";

?>

Return(!($var & 1)); } $array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5); $array2 = array(6, 7, 8, 9, 10, 11, 12); echo "Odd :n"; print_r(array_filter($array1, "odd")); echo "Even:n"; print_r(array_filter($array2, "even")); /* Odd : Array (   [a] => 1   [c] => 3   [e] => 5 ) Even: Array (   [0] => 6   [2] => 8   [4] => 10   [6] => 12 ) */ Filter out duplicate values ​​in PHP arrays To remove duplicate values ​​from an array, you can use the foreach method or the array_unique method. The following code uses both methods
The code is as follows Copy code
<🎜>$arrF = array();<🎜> $arrS = array();<🎜> $intTotal = 100;<🎜> $intRand = 10;<🎜> for($i=0; $i < $intTotal; $i++)<🎜> {<🎜> $arrF[] = rand(1, $intRand);<🎜> $arrS[] = rand(1, $intRand);<🎜> }<🎜> $arrT = array_merge($arrF, $arrS);<🎜> $arrRF = array();<🎜> $intStart = time();<🎜> foreach($arrT as $v)<🎜> {<🎜> if(in_array($v, $arrRF))<🎜> {<🎜> continue;<🎜> }<🎜> else<🎜> {<🎜> $arrRF[] = $v;<🎜> }<🎜> }<🎜> $intEnd = time();<🎜> $intTime = $intEnd-$intStart;<🎜> echo "With Continue,Spend time:$intTime
"; $intStart1 = time(); $arrRS = array_unique($arrT); $intEnd2 = time(); $intTime2 = $intEnd2-$intStart1; echo "With array_unique function,Spend time:($intTime2)"; echo "
";
print_r($arrT);
print_r($arrRF);
print_r($arrRS);
echo "
"; ?>


When $intTotal is relatively small, for example, within 1000, the value of $intRand basically does not affect the result, and the execution time of both is similar.

When testing $intTotal is greater than 10000 and $intRand is 100, the efficiency of using array_unique is higher than that of foreach loop judgment. $intRand=10, the execution time of the two is consistent.

Therefore, it can be concluded that when the array capacity is not large, probably within 1000, the execution efficiency of using the two is similar.

When the array capacity is relatively large (I have not tested the specific value, you can determine this value if you are interested), as $intRand gradually increases, array_unique performs better, I do not use $ The reason for the ratio of intTotal/$intRand is that it does not feel proportional to the change, but it basically follows that the larger the ratio, the better the performance of array_unique.

To sum up, when filtering duplicate values ​​in an array, it is recommended to use array_unuique. When the array is small, the two are equally efficient. Using array_unique will of course reduce your code by several lines. When the array capacity is too large, , the function performs better


Two-dimensional array deduplication function

PHP array removes duplicates. There is a built-in function array_unique (), but PHP's array_unique function only applies to one-dimensional arrays, not multi-dimensional arrays. The following provides an array_unique function for a two-dimensional array

The code is as follows
 代码如下 复制代码

function unique_arr($array2D,$stkeep=false,$ndformat=true)
{
 // 判断是否保留一级数组键 (一级数组键可以为非数字)
 if($stkeep) $stArr = array_keys($array2D);

 // 判断是否保留二级数组键 (所有二级数组键必须相同)
 if($ndformat) $ndArr = array_keys(end($array2D));

 //降维,也可以用implode,将一维数组转换为用逗号连接的字符串
 foreach ($array2D as $v){
  $v = join(",",$v);
  $temp[] = $v;
 }

 //去掉重复的字符串,也就是重复的一维数组
 $temp = array_unique($temp);

 //再将拆开的数组重新组装
 foreach ($temp as $k => $v)
 {
  if($stkeep) $k = $stArr[$k];
  if($ndformat)
  {
   $tempArr = explode(",",$v);
   foreach($tempArr as $ndkey => $ndval) $output[$k][$ndArr[$ndkey]] = $ndval;
  }
  else $output[$k] = explode(",",$v);
 }

 return $output;
}

测试

$array2D = array('first'=>array('title'=>'1111','date'=>'2222'),'second'=>array('title'=>'1111','date'=>'2222'),'third'=>array('title'=>'2222','date'=>'3333'));


print_r($array2D);
print_r(unique_arr($array2D,true));

Copy code
function unique_arr($array2D,$stkeep=false,$ndformat=true) {

// Determine whether to retain the first-level array key (the first-level array key can be non-numeric)

if($stkeep) $stArr = array_keys($array2D); // Determine whether to retain the secondary array keys (all secondary array keys must be the same) if($ndformat) $ndArr = array_keys(end($array2D)); //Dimensionality reduction, you can also use implode to convert a one-dimensional array into a string connected with commas foreach ($array2D as $v){ $v = join(",",$v); $temp[] = $v; } //Remove repeated strings, that is, repeated one-dimensional arrays $temp = array_unique($temp);
//Reassemble the disassembled array foreach ($temp as $k => $v)
{
if($stkeep) $k = $stArr[$k]; if($ndformat) { $tempArr = explode(",",$v); foreach($tempArr as $ndkey => $ndval) $output[$k][$ndArr[$ndkey]] = $ndval; } else $output[$k] = explode(",",$v); } return $output; } Test $array2D = array('first'=>array('title'=>'1111','date'=>'2222'),'second'=>array('title'=> ;'1111','date'=>'2222'),'third'=>array('title'=>'2222','date'=>'3333')); print_r($array2D); print_r(unique_arr($array2D,true)); http://www.bkjia.com/PHPjc/633131.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/633131.htmlTechArticleIn php, I will introduce to you two commonly used array filtering functions, array_filter and array_unique. One is to filter the array. Null value, one is to filter the duplicate value of the array, let's do it together now...
Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1279
29
C# Tutorial
1257
24
What happens if session_start() is called multiple times? What happens if session_start() is called multiple times? Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

The Compatibility of IIS and PHP: A Deep Dive The Compatibility of IIS and PHP: A Deep Dive Apr 22, 2025 am 12:01 AM

IIS and PHP are compatible and are implemented through FastCGI. 1.IIS forwards the .php file request to the FastCGI module through the configuration file. 2. The FastCGI module starts the PHP process to process requests to improve performance and stability. 3. In actual applications, you need to pay attention to configuration details, error debugging and performance optimization.

What is the significance of the session_start() function? What is the significance of the session_start() function? May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

Composer: Aiding PHP Development Through AI Composer: Aiding PHP Development Through AI Apr 29, 2025 am 12:27 AM

AI can help optimize the use of Composer. Specific methods include: 1. Dependency management optimization: AI analyzes dependencies, recommends the best version combination, and reduces conflicts. 2. Automated code generation: AI generates composer.json files that conform to best practices. 3. Improve code quality: AI detects potential problems, provides optimization suggestions, and improves code quality. These methods are implemented through machine learning and natural language processing technologies to help developers improve efficiency and code quality.

H5: Key Improvements in HTML5 H5: Key Improvements in HTML5 Apr 28, 2025 am 12:26 AM

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

How to use MySQL functions for data processing and calculation How to use MySQL functions for data processing and calculation Apr 29, 2025 pm 04:21 PM

MySQL functions can be used for data processing and calculation. 1. Basic usage includes string processing, date calculation and mathematical operations. 2. Advanced usage involves combining multiple functions to implement complex operations. 3. Performance optimization requires avoiding the use of functions in the WHERE clause and using GROUPBY and temporary tables.

Composer: The Package Manager for PHP Developers Composer: The Package Manager for PHP Developers May 02, 2025 am 12:23 AM

Composer is a dependency management tool for PHP, and manages project dependencies through composer.json file. 1) parse composer.json to obtain dependency information; 2) parse dependencies to form a dependency tree; 3) download and install dependencies from Packagist to the vendor directory; 4) generate composer.lock file to lock the dependency version to ensure team consistency and project maintainability.

Are all list operations supported by arrays, and vice versa? Why or why not? Are all list operations supported by arrays, and vice versa? Why or why not? Apr 26, 2025 am 12:05 AM

No,notalllistoperationsaresupportedbyarrays,andviceversa.1)Arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,whichimpactsperformance.2)Listsdonotguaranteeconstanttimecomplexityfordirectaccesslikearraysdo.

See all articles