I have four variables: $one_flag
, $two_flag
, $three_flag
, and $four_flag
. I'm using them as flags inside a for loop because I want to keep track of the last four iterations.
$one_flag = 1;
$two_flag = 0;
$three_flag = 0;
$four_flag = 0;
$a = array(1, 2, 3, 17, 27, 44, 45, 47, 49);
foreach ($a as $v) {
if ($one_flag){
$first_v = $v;
$one_flag = 0;
$two_flag = 1;
}
if ($two_flag){
$second_v = $v;
$two_flag = 0;
$three_flag = 1;
}
if ($three_flag){
$third_v = $v;
$three_flag = 0;
$four_flag = 1;
}
if ($four_flag){
$fourth_v = $v;
$four_flag = 0;
$first_flag = 1;
}
if ($v == 45){
# tricky part
print "The last three v's were: " . $first_v . ", " . $second_v . ", " . $third_v . "
";
}
}
Right now it prints The last three v's were 1, 1, 1
but it's supposed to print The last three v's were 45, 44, 27
. Also, the problem with the code above is I need to know which flag is equal to 1
(what flag we're currently on) so that I can print the correct statement.
For example, when $v == 45
, $first_v
is suppose to equal to 27; $second_v
is suppose to equal to 44; $fourth_v
is suppose to equal to 17; and third_v
is suppose equal to 45. I'd need to know $three_flag
is equal to 1 in order to print out "The last three were $second_flag, $first_flag, $fourth_flag" in that order.
How can I get my loop to work? How do I keep track of the last four iterations?
EDIT: I misspoke. I actually want to print The last three v's were 44, 27, 17