如果值在foreach内有多个相同的值,如何显示一个值?

时间:2018-01-08 06:33:12

标签: php

如果值在foreach内有多个相同的值,如何显示一个值?

$colors = array("red", "red", "green", "blue", "blue", "yellow"); 

foreach ($colors as $value) {
    echo "$value <br>";
}

在数组颜色值红色蓝色多个值中,所以我只想显示一个值。 红色,绿色,蓝色和黄色

4 个答案:

答案 0 :(得分:2)

array_unique() 用于从数组中删除重复值。

$colors = array("red", "red", "green", "blue", "blue", "yellow"); 

foreach (array_unique($colors) as $value) {
    echo "$value <br>";
}

答案 1 :(得分:1)

使用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

注意: - 如果您不想更改初始数组,请使用array_unique()内的foreach()

$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

答案 2 :(得分:1)

您可以使用下面的array_unique()功能。

试试这个:

{{1}}

答案 3 :(得分:1)

使用array_unique($arrayName)从数组中获取唯一(不同)值。

<?php 
   $colors = array("red", "red", "green", "blue", "blue", "yellow"); 
   foreach (array_unique($colors) as $value) {
       echo "$value <br>";
    }
?>