使用array_unique()
array_unique — 从数组中删除重复值
$colors = array("red", "red", "green", "blue", "blue", "yellow");
$colors = array_unique($colors);
foreach ($colors as $value) {
echo "$value <br>";
}
输出:- https://eval.in/932025
注意:- 如果您不想更改初始数组,请在 foreach() 中使用 array_unique()
$colors = array("red", "red", "green", "blue", "blue", "yellow");
foreach (array_unique($colors) as $value) {
echo "$value <br>";
}
输出:-https://eval.in/932027
或者您也可以创建一个新变量:-
$colors = array("red", "red", "green", "blue", "blue", "yellow");
$unique_colors = array_unique($colors);
foreach ($unique_colors as $value) {
echo "$value <br>";
}
输出:- https://eval.in/932028