mercredi 16 mai 2018

How to loop through a foreach until X is found, if not found, look for Y

Sorry if this is a duplicate, I can't figure out what to search for to find the answer.

I have a foreach loop, and in that loop, I'm attempting to test if (A == B). Then once found I break the loop. If (A != B) in an iteration, I test if (X == Y).

My problem is that if (X == Y) is found to be true first, the loop breaks before if (A == B) can be tested.

Is there a better way to accomplish this task?

$variable[1] = ['A' => 'n', 'X' => 'n'];
$variable[2] = ['A' => 'n', 'X' => 'Y'];
$variable[3] = ['A' => 'B', 'X' => 'n'];

$test = 'B';

foreach ($variable as $value) {

    if($value['A'] == $test || $value['X'] == "Y") {
        echo 'The results: ' . $value['A'];
        break;
    }

}

// The results for $variable[2] are returned. I need the results for $variable[3] to be returned.

I did have an else statement which worked fine, but I was having to duplicate the output.

Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire