PHP数组唯一类型检查 [英] php array unique type check
本文介绍了PHP数组唯一类型检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 array_unique
摆脱数组中的重复值.但是,问题是 array_unique
在检查重复项时没有考虑数据类型.例如:
I am using array_unique
to get rid of the duplicate values in an array. But, the problem is array_unique
does not consider data types while checking for duplicates. For example:
$a = [1, true, null, false];
$u = array_unique($a);
var_dump($u);
输出:
array(2) {
[0] =>int(1)
[2] =>NULL
}
但是,如果考虑数据类型,则数组的每个值都是唯一的.我知道我可以通过运行循环来解决此问题.但是,有没有一种更好的方法或替代 array_unique
的方法来实现这一目标?
But, if you consider data types every value of the array are unique. I know I can fix this by running a loop. But, is there a better way or an alternative to array_unique
by which I can achieve this?
推荐答案
我很无聊:)
$a = ['test',1, true, null, false,null,'test',true];
function arrayUnique($a)
{
$u=array();
foreach ($a as $k => $v) {
if(!in_array($v,$u,TRUE)){
$u[]=$v;
}
}
return $u;
}
var_dump(arrayUnique($a));
输出:
array(5) { [0]=> string(4) "test" [1]=> int(1) [2]=> bool(true) [3]=> NULL [4]=> bool(false) }
这篇关于PHP数组唯一类型检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文