简体   繁体   中英

if condition with foreach loop for array in php

is it any way to stop this repeated data.

if ($employees_csa[0]->csa_taken == 2 && $employees_csa[1]->csa_taken == 2 && $employees_csa[2]->csa_taken == 2 && $employees_csa[3]->csa_taken == 2 && $employees_csa[4]->csa_taken == 2 && $employees_csa[5]->csa_taken == 2 && $employees_csa[6]->csa_taken == 2 && $employees_csa[7]->csa_taken == 2) {
          echo "data";
    }

i tried for key range(0 , 8) like this

foreach (range(0, count($employees_csa)) as $number) {
                        
    if ($employees_csa[$number]->csa_taken == 2) {
            echo "data";
                           
      }
   }

i tried that way not get any succes. i any another way to write easy condition.

You can loop arrays out of the box :

$all_taken = true;
foreach ($employees_csa as $employee) {
    if ($employee->csa_taken != 2) {
        $all_taken = false;
        break;
    }
}
if ($all_taken) {
    echo 'data';
}

Another approach would be array_reduce() but this doesn't abort looping when there's already an answer:

$all_taken = array_reduce($employees_csa, function ($all_taken, $employee) {
    if ($employee->csa_taken != 2) {
        return false;
    }
    return $all_taken;
}, true);
if ($all_taken) {
    echo 'data';
}

Alternatively, you could do it like this using array_column to pull out all the csa_taken properties, then reducing to 1 item if they are all the same with array_unique() and then checking that the same value is the expected number 2 with reset() .

$csa_taken = array_column($employees_csa, 'csa_taken');

if (reset($csa_taken) === 2 && count(array_unique($csa_taken)) === 1) {
    echo 'data';
}

Reusable function version: https://3v4l.org/4kYiE

A simple for-loop could work

$condition_met=true;

for($i=0;$i<8;++$i){
  if( $employees_csa[$i]->csa_taken != 2){
  $condition_met=false;
  break;
  }
}
if($condition_met===true){
   //success
   }
else{
   //fail
   }

A simple method could be done like

foreach($employees_csa as $singleEmployee){
    if($singleEmployee->csa_taken == 2){
        echo "data";
    }
}

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