skip to Main Content

it might be a stupid question but I am failing to combine some elseifs. I’m sure there must be smarter way. Do you have an idea?

<?php
$level_ids = leaky_paywall_subscriber_current_level_ids();

if (!empty($level_ids)) {
    if (in_array(2, $level_ids)) {
    echo 'DO THIS';
    }
    elseif (in_array(3, $level_ids)) {
    echo 'DO THIS';
    }
    elseif (in_array(4, $level_ids)) {
    echo 'DO THIS';
    }
    elseif (in_array(6, $level_ids)) {
    echo 'DO THIS';
    }
    elseif (in_array(7, $level_ids)) {
    echo 'DO THIS';
    }
    elseif (in_array(9, $level_ids)) {
    echo 'DO THIS';
    }
    elseif (in_array(10, $level_ids)) {
    echo 'DO THIS';
    }
    else {
    echo 'DO THAT';
    }
}
                                      
?>

I tried to combine that much smarter but it doesn’t work.

Thank yopu so much for helping put!

3

Answers


  1. Define an array of what each should do,like this!

    <?php
    
    function someFunction(): string
    {
        return 'hello';
    }
    
    function doSomething(): string
    {
        return 'howdy';
    }
    
    function doSomethingElse(): string
    {
        return 'hi';
    }
    
    $levels = [
      1 => 'someFunction',
      2 => 'doSomething',
      3 => 'doSomethingElse',
    ];
    
    $level = 1;
    
    if (array_key_exists($level, $levels)) {
        $toCall = $levels[$level];
    
        echo $toCall() . "n";
    } else {
        echo 'unknown code';
    }
    

    Try it out here https://3v4l.org/KBDRJ

    Login or Signup to reply.
  2. There is nothing wrong with the way you wrote it. I would have formatted the code slightly differently according to the One True Brace Style, but that’s because I’ve been around forever:

    if (...) {
      echo 'DO THIS';
    } elseif (...) {
      echo 'DO THIS';
    } else {
      echo 'DO THAT';
    }
    
    Login or Signup to reply.
  3. if ([] === array_intersect([ 2, 3, 4, 6, 7, 9, 10 ], leaky_paywall_subscriber_current_level_ids())) {
      echo 'DO THAT';
    } else {
      echo 'DO THIS';
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search