PHP custom function to find array difference (more efficient than array_diff function)

WBOY
Release: 2016-07-25 08:57:08
Original
1254 people have browsed it
This article introduces a custom function array_different for finding the array difference, which is more efficient than the array_diff function. Friends in need can refer to it.

php finds the array difference, the code is as follows:

<?php
/**
* func: array_different
* 功能:求数组的差集
* edit:bbs.it-home.org
*/
function array_different($array_1, $array_2) {
$array_2 = array_flip($array_2); //将数组键值调换

foreach ($array_1 as $key => $val) {
if (isset($array_2[$val])) {
unset($array_1[$key]);
}
}

return $array_1;
}

function runtime($mode = 0) {
static $t;

if (!$mode) {
$t = microtime();
return;
}

$t1 = microtime();
list($m0, $s0) = explode(" ", $t);
list($m1, $s1) = explode(" ", $t1);

return sprintf("%.3f", ($s1 + $m1 - $s0 - $m0) * 1000);
}

$array_1 = array();
$array_2 = array();

for ($i = 0; $i <= 5000; $i++) {
$array_1[$i] = mt_rand(0, 100);
$array_2[$i] = mt_rand(0, 100);
}

runtime(); //计时开始
$arr_diff = array_diff($array_1, $array_2);
echo runtime(1); //计时结束并输出计时结果
echo '<br>';

foreach ($arr_diff as $key => $val) {
echo $val.',';
}

runtime(); //计时开始
$arr_diff2 = array_different($array_1, $array_2);
echo runtime(2); //计时结束并且输出计时结果

foreach ($arr_diff2 as $key => $val) {
echo $val.',';
}
?>
Copy after login


source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!