简体   繁体   中英

Echo once per foreach

So I have the following code:

$colors=$ex->Get_Color("images/avatarimage3.png", $num_results, $reduce_brightness, $reduce_gradients, $delta);
foreach ( $colors as $hex => $count )
{
    if ($hex == 'e6af23' && $count > 0.05) 
    { 
        echo "The image has the correct colour"; 
    } 
    else 
    { 
        echo "The image doesn't have the correct colour"; 
    }
}

Basically this code at the moment grabs the hex value and percentage of colours than image contains and adds them to an array. The code above looks to see if the hex is a certain value and the percent above 5% and if it is then it displays the success message. This part works exactly as it should do!

Now, what I also want is that if the colour isn't correct, so for all other hex values in the array other than $hex == 'e6af23' I want it to display a failure message but only display it once and not for every time the hex isn't that value.

Basically I need it so that the failure message is only displayed once and not 5 times (the number of hex colours in the image).

You can use a flag to indicate if the message has been outputted or not, and if so then don't output again:

$colors=$ex->Get_Color("images/avatarimage3.png", $num_results, $reduce_brightness, $reduce_gradients, $delta);
$error_displayed = false;
foreach ( $colors as $hex => $count ) {
    if ($hex == 'e6af23' && $count > 0.05) {
        echo "The image has the correct colour";
    } else if (!$error_displayed) {
        echo "The image doesn't have the correct colour";
        $error_displayed = true;
    }
}

Just keep a list of colors you already echoed.

$failed = array();

forech ($colors as $hex) {
    if (!in_array($hex, $failed) && $error) {
        echo 'Failed at hex ' . $hex;
        $failed[] = $hex;
    }
}

Using NewFurnitureRay's answer as a guideline I came up with this answer:

$colors=$ex->Get_Color("images/avatarimage.png", $num_results, $reduce_brightness, $reduce_gradients, $delta);
$success = true;
foreach ( $colors as $hex => $count ) {
if ($hex !== 'e6af23') {$success = false; }
if ($hex == 'e6af23' && $count > 0.05) {$success = true; break;}
}

if ($success) { echo "Success"; } else { echo "This is a failure"; }

Seems to work now as it should only displaying either a success or a failure regardless of the success's position in the array :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM