Using an If-else within an array

后端 未结 10 1903
滥情空心
滥情空心 2020-12-11 04:45

Hi guys I have no idea if this is possible or if there is another way of doing it but any help would be appreciated. What I\'m trying to do is turn off arrays individually.

相关标签:
10条回答
  • 2020-12-11 05:22

    What you are suggesting is not possible. You would need to add the variables base on the if/else conditional after you have made the array.

    For example:

    $arrLayout = array();
    
    if($LibraryStatus) {
        $arrLayout['section1'] = array("wLibrary" => array(
                "title" => "XBMC Library",
                "display" => ""
            ));
    }
    

    This still rather untidy because of your array structure, I'd try eliminating some keys if you can, for example do you need section1? You could just let PHP add a numerical key by doing $arrLayout[] = array(..), which create a new 'row' in the array which you can still loop through.

    0 讨论(0)
  • 2020-12-11 05:25

    You are complicating things needlessly.

    If the condition and the values you want to assign are simple enough, you can use the ternary operator (?:) like so:

    $condition = true;
    $arrLayout = array(
        "section1" => $condition ?
                         array(
                             "wLibrary" => array(
                                 "title" => "XBMC Library",
                                 "display" => ""
                             )
                         ) : false,
    )
    

    However, this is not very readable even for simple cases and I would call it a highly questionable practice. It's much better to keep it as simple as possible:

    $condition = true;
    $arrLayout = array(
        "section1" => false
    );
    
    if($condition) {
        $arrLayout["section1"] = array(
                                      "wLibrary" => array(
                                         "title" => "XBMC Library",
                                         "display" => ""
                                      )
                                 );
    }
    
    0 讨论(0)
  • 2020-12-11 05:31

    Inside an array you can use ternary operator:

    $a = array(
        'b' => $expression == true ? 'myWord' : '';
    );
    

    But in your example better way is to move if-statement outside your array.

    0 讨论(0)
  • 2020-12-11 05:31

    You could use push?

    <?php
    
    $LibraryStatus='true'
    
    $arrLayout = array();
    if ($LibraryStatus=='true') {
    push($arrLayout["section1"], array(
            "wLibrary" => array(
                "title" => "XBMC Library",
                "display" => ""
            ));
    }
    ?>
    
    0 讨论(0)
提交回复
热议问题