Q:

Php If Condition in Array

I am trying to built an if condition in my array currently looks like this but does not work.
protected $menuItems = [
    'items' => [
        [
            'title' => 'test',
        ],
        $this->hasma() ? [
            'title' => 'Ma',
        ] : null,
    ],
]

Basically hasma returns true or false, if it is true it shall add the above and if it is false I shall return (add) nothing.

A:

you can try the following:
protected $menuItems = [
    'items' => [
        [
            'title' => 'test',
        ]
    ]
]

if($this->hasma())
    $menuItems['items'][] = ['title' => 'Ma']

When looking the code, i noticed that you used the keyword "protected" which involve that you're hardcoded the value of your class property in the declaration.
Instead, you should initialize all your propertys in contructor method.
The code would look like this :
 <?php

class A
{

    protected $menuItems;

    function __construct()
    {
        $this->menuItems = [
            'items' => [
                ['title' => 'test']
            ]
        ];

        if($this->hasma())
            $menuItems['items'][] = ['title' => 'Ma'];
    }
}

?>

