How can I add a condition inside a php array?

前端 未结 8 986
小鲜肉
小鲜肉 2020-12-10 00:49

Here is the array

$anArray = array(
   \"theFirstItem\" => \"a first item\",
   if(True){
     \"conditionalItem\" => \"it may appear base on the condi         


        
8条回答
  •  我在风中等你
    2020-12-10 01:22

    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.

提交回复
热议问题