0

I want to loop only if points are greater than levels. The result I want is "reward0"

The sum of points is 80 so greater than 50 but less than 100 so only one reward is required.

I tried like this but no luck.

$levels = [50, 100, 150, 200];
$points = 0;
$rewards = [];


foreach ($levels as $key => $level) {

    if($points >= $level) { 
        $rewards[] = 'reward' . $key;
    }

    // 20, 40, 60, 80
    $points += 20; 

}

return $rewards;
5
  • Please expand on no luck. Do you get an error? Is this in a function? return maybe should be print_r? Also not clear about points is 80 so greater than 50 but less than 100 Commented May 10, 2020 at 14:53
  • 1
    Can you please explain the Logic clearer? I could not nderstand the logic. Commented May 10, 2020 at 14:53
  • In the above code, the execution will not enter into the if condition. That is, the if condition never becomes true. Thus $rewards array will be always empty. Commented May 10, 2020 at 14:55
  • @HarishST Thanks for your comment. How to make working? Commented May 10, 2020 at 14:57
  • First please explain what is your goal in a better way, so we can understand the issue and come up with a solution for you. Commented May 10, 2020 at 14:59

1 Answer 1

2

If I understand your logic, then this is what you want,

<?php
$levels = [50, 100, 150, 200];
$points = 0;
$rewards = [];
$points = count($levels) * 20;
$rewards = array_filter($levels, function($n) use ($points){ 
    return $n < $points;
});
print_r($rewards);

DEMO: https://3v4l.org/3VJTR

Sign up to request clarification or add additional context in comments.

3 Comments

If this is the logic, why we need to use foreach? We can simply discard foreach and replace it with $points = count($levels) * 20;. Right?
@HarishST Sir, EDITED :)
@AlwaysSunny Ha ha. I am just making sure there is a better way for OP. For him, it may be new. By the way, Thanks for the Edit Sir. ;) And you are the first one who understand the OP's question and that's great.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.