dimanche 7 octobre 2018

Loop through an if statement?

I'm creating user levels based on how many days a user is registered. That way I want to create messages such as "happy first anniversary on this website" etc.

So far I built it with code like below.

// count days
$interval_obj->days;  // final variable counting the days a user has registered. e.g. 50 days

// array of number of levels. e.g. 25
$levels = apply_filters( 'hook_member_levels', array(       
    '1' => esc_html__('1 Level', $this->textdomain), 
    '2' => esc_html__('2 Levels', $this->textdomain),
    //...etc
) );

$one_min    = $option['level-1-min']; // e.g. 1 day
$one_max    = $option['level-1-max']; // e.g. 30 days
$two_min    = $option['level-2-min']; // e.g. 31 days
$two_max    = $option['level-2-max']; // e.g. 90 days
...etc.

if( $interval_obj->days >= $one_min && $interval_obj->days <= $one_max ) {             
    $output = 'level-1';
} elseif( $interval_obj->days >= $two_min && $interval_obj->days <= $two_max ) { 
    $output = 'level-2';
} elseif(){
    //... etc.
}

Outcome; the current user will fall in level 2 (50 days).

Although this works, I'm looking for a more efficient/cleaner way to code this (like inside a loop) Something like this:

$how_many_levels = count( $levels );    

for( $i = 0; $i <= $how_many_levels; $i++ ) {

    ${ $i .'_min' } = $option['level-'.$i.'-min'];
    ${ $i .'_max'} = $option['level-'.$i.'-max'];

    if( $interval_obj->days >= ${ $i .'_min' } && $interval_obj->days <= ${ $i .'_max' } ) { 
        $output = 'level-'.$i;
    } else {
        $output = '0';
    }

}

return $output;

Needless to say, this doesn't work. $i is 25 (number of levels), not 1,2,3,4...25. So this code reads as

if( $interval_obj->days >= 9125 && $interval_obj->days <= 9490 ) { 
    $output = 'level-25';
} else {
    $output = '0';
}

Outcome is 0 because the user is only registered for 50 days.

Is there are better approach (that works)?

Aucun commentaire:

Enregistrer un commentaire