38

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 ')'
0

9 Answers 9

53

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";
Sign up to request clarification or add additional context in comments.

1 Comment

$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
6

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.

Comments

4

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.

3 Comments

This is more cleaner answer.. But then it is against PSR
@numediaweb which PSR?
3

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",
    ]
);

Comments

2

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

Comments

2

You can assign all values and filter empty keys from the array at once like this:

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

This allows you avoid the extra conditional after the fact, maintain key order, and imo it's fairly readable. The only caveat here is that if you have other falsy values (0, false, "", array()) they will also be removed. In that case you may wish to add a callback to explicitly check for NULL. In the following case theLastItem won't get unintentionally filtered:

$anArray = array_filter([
    "theFirstItem" => "a first item",
    "conditionalItem" => $condition ? "it may appear base on the condition" : NULL,
    "theLastItem"  => false,
], function($v) { return $v !== NULL; });

Comments

0

You can do it like this:

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

unset the EMPTY array item if the condition is false

unset($anArray['EMPTY']);

Comments

0

Its pretty simple. Create array with essential elements. Then add conditional elements to the array. Now add other elements if required.

$anArray = array(
    "theFirstItem" => "a first item"
);

if(True){
    $anArray+=array("conditionalItem" => "it may appear base on the condition");
}

$more=array(
    "theLastItem"  => "the last item"
); 

$anArray+=$more;

You modify this code to make it even more shorter,, i have just given elaborated code to make it self explantory. No NULL element, no empty string, put you item anywhere you want, no hassel.

Comments

-1

You can use array_merge

$result = array_merge(
    ['apple' => 'two'],
    (true ? ['banana' => 'four'] : []),
    (false ? ['strawberry' => 'ten'] : [])
);

print_r($result);

// Output:
/* 
Array
(
    [apple] => 'two'
    [banana] => 'four'
) 
*/

Drawback of array_merge: Values in an array with numeric keys will be renumbered with incrementing keys starting from zero in the result array. You can use the union operator instead to maintain the original numeric keys

Or by using Array Union Operator

$result = ['apple' => 'two'] + (true ? ['banana' => 'four'] : []) + (false ? ['strawberry' => 'ten'] : []);

print_r($result);

// Output:
/* 
Array
(
    [apple] => 'two'
    [banana] => 'four'
) 
*/

Note: When using the union operator, remember that for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.

2 Comments

These approaches were given 7 years ago on this same page. stackoverflow.com/a/27872484/2943403
oops, I didn't see that. Thanks for mentioning. I will remove or update this answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.