ChaseC
ChaseC

Reputation: 426

For loop extra condition

I have a for loop that goes through a couple of arrays and assigns some values after doing some basic math. My question is: Is there a way to make sure that this for loop ONLY iterates while an additional condition is true?

for ($i = 0; $i < count($ci); $i++) {
    $PIDvalue = $ci[$i]["PID"];
    $datevalue = $pi[$i]["datetime"];
    $pp_tcvalue = $ci[$i]["pp_tc"] - $pi[$i]["pp_tc"];
    $pp_trvalue = $ci[$i]["pp_tr"] - $pi[$i]["pp_tr"];
    $bp_tcvalue = $ci[$i]["bp_tc"] - $pi[$i]["bp_tc"];
    $emailvalue = $ci[$i]["email"];

So I want something like this...

    for ($i = 0; $i < count($ci); $i++) {
    if($ci[$i]["email"] === $pi[$i]["email"]) {
    $PIDvalue = $ci[$i]["PID"];
    $datevalue = $pi[$i]["datetime"];
    $pp_tcvalue = $ci[$i]["pp_tc"] - $pi[$i]["pp_tc"];
    $pp_trvalue = $ci[$i]["pp_tr"] - $pi[$i]["pp_tr"];
    $bp_tcvalue = $ci[$i]["bp_tc"] - $pi[$i]["bp_tc"];
    $emailvalue = $ci[$i]["email"];

If they don't match, I would assign a value of "0" or something.

Upvotes: 0

Views: 277

Answers (2)

blue112
blue112

Reputation: 56442

You can add that in your for condition, like that :

for ($i = 0; $i < count($ci) && $ci[$i]["email"] === $pi[$i]["email"]; $i++) {

When the second condition computes to false, the loop will stop running.

Upvotes: 1

CodeManX
CodeManX

Reputation: 11865

You could add an additional condition to the for-loop, making it pretty much unreadable:

for ($i = 0; $i < count($ci), $ci[$i]["email"] === $pi[$i]["email"]; $i++)

but I would rather break the loop:

for ($i = 0; $i < count($ci); $i++) {
    if ($ci[$i]["email"] !== $pi[$i]["email"]) break;
    $PIDvalue = ...

Upvotes: 1

Related Questions