Reputation: 13
I need some assistance with my code logic: The expected output of the following code is 1110, how to achieve that value?
<?php
$user_accepted_events = [1,2,3];
$all_events = [1,2,3,4];
//Nested foreach loop for testing if the user accepted an event
foreach ($all_events as $single_row) {
foreach ($user_accepted_events as $user_single_id) {
if ($single_row == $user_single_id) { //This prints expected value
print_r("1"); //User has accepted event
} else { //Here it logically print's 0 nine times
print_r("0"); //User has not accepted Event
}
}
}
//Expected Output is 1110
//Real Output is 100010001000
?>
Thanks.
Upvotes: 1
Views: 59
Reputation: 16453
You've got a logical error in your code: you are printing 1
or 0
for every permutation of both loops.
As there are 4 items in the outer loop and 3 in the inner, you are receiving 12 outputs.
Instead, keeping the same approach you have already adopted, you can capture whether the user has attended the event in a variable, and break if so.
Then once for each of the outer loops, output the result:
$user_accepted_events = [1,2,3];
$all_events = [1,2,3,4];
foreach ($all_events as $single_row) {
$hasAccepted = false;
foreach ($user_accepted_events as $user_single_id) {
if ($single_row == $user_single_id) {
$hasAccepted = true;
break;
}
}
print_r($hasAccepted ? 1 : 0);
}
Output:
1110
Upvotes: 1
Reputation: 57141
As you have nested loops - it will compare each item against every nested item and most of them won't match - producing multiple results for each item.
Instead - use in_array()
to check each item...
foreach ($all_events as $single_row) {
if ( in_array($single_row, $user_accepted_events)) {
print_r("1"); //User has accepted event
} else {
print_r("0"); //User has not accepted Event
}
}
Upvotes: 3