How can I add a condition inside a php array?

51,663

Solution 1

Unfortunately that's not possible at all.

If having the item but with a NULL value is ok, use this:

$anArray = array(
   "theFirstItem" => "a first item",
   "conditionalItem" => $condition ? "it may appear base on the condition" : NULL,
   "theLastItem"  => "the last item"
);

Otherwise you have to do it like that:

$anArray = array(
   "theFirstItem" => "a first item",
   "theLastItem"  => "the last item"
);

if($condition) {
   $anArray['conditionalItem'] = "it may appear base on the condition";
}

If the order matters, it'll be even uglier:

$anArray = array("theFirstItem" => "a first item");
if($condition) {
   $anArray['conditionalItem'] = "it may appear base on the condition";
}
$anArray['theLastItem'] = "the last item";

You could make this a little bit more readable though:

$anArray = array();
$anArray['theFirstItem'] = "a first item";
if($condition) {
   $anArray['conditionalItem'] = "it may appear base on the condition";
}
$anArray['theLastItem'] = "the last item";

Solution 2

If you are making a purely associative array, and order of keys does not matter, you can always conditionally name the key using the ternary operator syntax.

$anArray = array(
    "theFirstItem" => "a first item",
    (true ? "conditionalItem" : "") => (true ? "it may appear base on the condition" : ""),
    "theLastItem" => "the last item"
);

This way, if the condition is met, the key exists with the data. If not, it's just a blank key with an empty string value. However, given the great list of other answers already, there may be a better option to fit your needs. This isn't exactly clean, but if you're working on a project that has large arrays it may be easier than breaking out of the array and then adding afterwards; especially if the array is multidimensional.

Solution 3

Your can do it like this:

$anArray = array(1 => 'first');
if (true) $anArray['cond'] = 'true';
$anArray['last'] = 'last';

However, what you want is not possible.

Solution 4

There's not any magic to help here. The best you can do is this:

$anArray = array("theFirstItem" => "a first item");
if (true) {
    $anArray["conditionalItem"] = "it may appear base on the condition";
}
$anArray["theLastItem"]  = "the last item";

If you don't care specifically about the order of the items, it gets a little more bearable:

$anArray = array(
    "theFirstItem" => "a first item",
    "theLastItem"  => "the last item"
);
if (true) {
    $anArray["conditionalItem"] = "it may appear base on the condition";
}

Or, if the order does matter and the conditional items are more than a couple, you can do this which could be considered more readable:

$anArray = array(
    "theFirstItem" => "a first item",
    "conditionalItem" => "it may appear base on the condition",
    "theLastItem"  => "the last item",
);

if (!true) {
    unset($anArray["conditionalItem"]);
}

// Unset any other conditional items here

Solution 5

Try this if you have associative array with different keys:

$someArray = [
    "theFirstItem" => "a first item",
] + 
$condition 
    ? [
        "conditionalItem" => "it may appear base on the condition"
      ] 
    : [ /* empty array if false */
] + 
[
    "theLastItem" => "the last item",
];

or this if array not associative

$someArray = array_merge(
    [
        "a first item",
    ],
    $condition 
        ? [
            "it may appear base on the condition"
          ] 
        : [ /* empty array if false */
    ], 
    [
        "the last item",
    ]
);
Share:
51,663
Tattat
Author by

Tattat

Updated on March 28, 2020

Comments

  • Tattat
    Tattat about 4 years

    Here is the array

    $anArray = array(
       "theFirstItem" => "a first item",
       if(True){
         "conditionalItem" => "it may appear base on the condition",
       }
       "theLastItem"  => "the last item"
    
    );
    

    But I get the PHP Parse error, why I can add a condition inside the array, what's happen??:

    PHP Parse error:  syntax error, unexpected T_IF, expecting ')'
    
  • numediaweb
    numediaweb over 6 years
    This is more cleaner answer.. But then it is against PSR
  • Awais fiaz
    Awais fiaz over 5 years
    second one seems lit
  • Raman Kant Vashisht
    Raman Kant Vashisht almost 5 years
    $anArray = array( "theFirstItem" => "a first item", "conditionalItem" => $condition ? "it may appear base on the condition" : NULL, "theLastItem" => "the last item" ); Its perfect for me, Thanks
  • Alex78191
    Alex78191 over 2 years
    @numediaweb which PSR?
  • mickmackusa
    mickmackusa about 2 years