php 为什么foreach循环echo every结果

but5z9lq  于 2023-06-20  发布在  PHP
关注(0)|答案(1)|浏览(96)

我想在这个循环中只得到我的数组的精确结果:

<?php

        $color_groups = [
            "green" => array('lightgreen', 'green', 'olive', 'malachite'),
            "blue" => array('blue', 'skyblue', 'cyan', 'iris', 'navyblue', 'zaffre')
        ];

        $selected_color_str = 'cyan';

        foreach ($color_groups as $key => $value) {
            foreach ($value as $color) {
                if (preg_match('/' . $color . '/i', $selected_color_str)) {
                    echo $key;
                } else {
                    echo " not_found ";
                }
            }
        }

        ?>

结果:

not_found not_found not_found not_found not_found not_found not_found蓝色not_found not_found not_found not_found

  • 但我想只显示blueif exists in that array,if not just echo not_found
1l5u6lss

1l5u6lss1#

在每次检查时输出一个not_found消息,您只需要在检查完所有选项后执行此操作。
您还可以在每个组中使用in_array()来检查,而不是查看每个元素。
所以...

// Store for the group key that matches
$matched_group = '';

foreach ($color_groups as $group => $colour_options) {
    if (in_array($selected_color_str, $colour_options)) {
        $matched_group = $group;
        // You can stop looking once found
        break;
    }
}

if ($matched_group) {
    echo 'Found ' . $matched_group;
} else {
    echo 'Not found';
}

相关问题