【问题标题】:How to display one value if value have more than one value that same inside foreach?如果值在foreach中具有多个相同的值,如何显示一个值?
【发布时间】:2023-03-30 05:37:02
【问题描述】:

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

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

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

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

【问题讨论】:

  • 使用array_unique

标签: php


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • @silviazulinka 很高兴为您提供帮助:):)
    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

      您可以使用array_unique() 函数,如下所示。

      试试这个:

      <?php 
      $colors = array("red", "red", "green", "blue", "blue", "yellow"); 
      $colors = array_unique($colors);
      print_r($colors);
      ?>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-06-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多