简体   繁体   中英

PHP, Echo only one time in a foreach loop

i'have an array, and then i have a script who gets the category i'm browsing (using wordpress) and put it in the $category variable.

So i test if the category i'm browsing it's equal to the $array key and then i paste some text

$array = array ('key' => 'value', ... )

//...
// a script who gets the category i'm browsing and store it in the $category variable    
//...
/* starting the foreach loop */
foreach( $array as $key => $value) {
            if ($category == $key) {
                echo "some $value here";    
            } elseif ($category !== $key) {
                echo "nothing"; 
            }

The problem is that this loop does echo "nothing" for each time the $category is not equal to the $key for each element of the array.

So if i have 20 key => value in the array this loop paste one time "some $value here" and 19 times "nothing"

there is a way to echo "nothing" only one time?

Thank you!

You can use array_key_exists instead of the foreach loop:

if (array_key_exists($category, $array)) {
    echo $array[$category];
} else {
    echo 'nothing';
}
    $i=0;
    foreach( $array as $key => $value) {
$i++;
                if ($category == $key) {
                    echo "some $value here";    
                } elseif($category !== $key)
                {
                  if($i<=1)
    {
                    echo "nothing"; 
    }
    else{}
                }

Try with -

$i = 1;
foreach( $array as $key => $value) {
            if ($category == $key) {
                echo "some $value here";    
            } elseif ($category !== $key) {
                $i++; 
            }
}
if (count($array) == $i) {
    echo "nothing";
}

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