Using an If-else within an array

Yes, this is possible using a certain shorthand:

<?php

$LibraryStatus = $ControlStatus = true;

$arrLayout = array(
             "section1" => array(
             ($LibraryStatus ? array("wLibrary" => array("title"   => "XMBC Library",
                                                         "display" => "")) : false),
             ($ControlStatus ? array("wControl" => array("title"   => "Control",
                                                         "display" => "")) : false)));

print_r($arrLayout);

?>

It works like this:

if($a == $b){ echo 'a'; }else{ echo 'b'; }

is equal to

echo $a == $b ? 'a' : 'b';

If you use this shorthand it will always return the output, so you can put it between brackets and put it inbetween the array.

http://codepad.org/cxp0M0oL

But for this exact situation there are other solutions as well.


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.


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" => ""
                                  )
                             );
}