简体   繁体   中英

Counting values in a conditional statement withing a foreach loop

I have the following foreach loop:

foreach($socialNetworks as $socialNetworksKey){    
    if($userUrl == NULL){
      echo $snName . ' is empty.' .  '<br/>';
     $value = 1;
    }
   elseif (strpos($userUrl,$snUrl) === false) { 
     echo $snName . '</b> address must start with <b>' . $snUrl  .  '</b><br/>';}
   else {
    echo 'Values are correct' .  '<br/>';
    $value = 1;
   }
 echo 'Value equals ' . count($value) .  '<br/>';
 }

The foreach loop source is an array. The foreach loop works correctly as desired.

Though I wish that I get the count/sum of the value of $value. For example if the 'if' and 'else' statements for the arrays are correct and I have 4 arrays this would count to 4. If 3 out of 4 arrays are correct the sum would be 3.

I tried using this and it worked here but when I echo it is displaying all the numbers from one and doing a summation all the time, but I want only to count $value and display the final value;

You need to put the echo outside of the foreach loop. I would do the following:

$value = 0;
foreach($socialNetworks as $socialNetworksKey){    
    if($userUrl == NULL){
      echo $snName . ' is empty.' .  '<br/>';
      $value++;
    }
   elseif (strpos($userUrl,$snUrl) === false) { 
      echo $snName . '</b> address must start with <b>' . $snUrl  .  '</b><br/>';}
   else {
      echo 'Values are correct' .  '<br/>';
      $value++;
   }
 }
 echo 'Value equals ' . $value .  '<br/>';

I think it should be

$value += 1;

which is the same as

$value = $value + 1;

instead of

$value = 1;

and you should put this line outside of foreach loop

echo 'Value equals ' . count($value) .  '<br/>';

So you should have this.

foreach($socialNetworks as $socialNetworksKey){    
    if($userUrl == NULL){
        echo $snName . ' is empty.' .  '<br/>';
        $value += 1;
    }elseif (strpos($userUrl,$snUrl) === false) { 
        echo $snName . '</b> address must start with <b>' . $snUrl  .  '</b><br/>';}
    else {
        echo 'Values are correct' .  '<br/>';
        $value += 1;
    }
}
echo 'Value equals ' . count($value) .  '<br/>';

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