I want to put a condition in an array, which in turn has two other arrays:
$context['columns'] = array(
// @TODO '' => ???
'name' => array(
'label' => '',
'width' => '2'
),
'image' => array(
'label' => '',
'width' => '2'
),);
I want to put the condition in the subarray image, I have tried to put it in ternary form, but it does not give me results, how could I do it?
My bad try…
$context['columns'] = array(
// @TODO '' => ???
'name' => array(
'label' => '',
'width' => '2'
),
1==2 ? 'image' : '' => array(
'label' => '',
'width' => '2'
),);
other try…
$context['columns'] = array(
// @TODO '' => ???
'name' => array(
'label' => '',
'width' => '2'
),
1==2 ? 'image' => array(
'label' => '',
'width' => '2'
),:'' );
>Solution :
Generally speaking, initializing data is only allowed to be done with immediate and invariant values, so I wouldn’t expect that to work well. It’s also not very readable.
I would instead consider creating a function that returns the array initialized and call that.
function initializeTheArray(...) {
$theArray = array();
$theArray['name'] = array( 'label' => '', 'width' => '2');
if( 1==2 ) {
$theArray['image'] = array('label' => '','width' => '2');
} else {
// this probably isn't what you want, but it was in your example.
$theArray[''] = array('label' => '','width' => '2');
}
return $theArray;
}
$context['columns'] = initializeTheArray( <whatever> );
Being an old curmudgeonly programmer type, I would appreciate this better, because you can separate it from the rest of your code and test it if necessary, and as the logic starts getting more complicated it’s easier to adapt to new use cases.
You might be able to figure out a "shorter" in terms of keystrokes way to do evaluate the initialization, but my goodness I would not want to be the one trying to debug the "compiler love letter"* that you create in the process.
- compiler love letter – something that is allowed by the syntax that can’t easily be read or understood for the logic that it represents. It lacks structure to tell future readers what precisely is happening, or why it was important, and thus becomes a maintenance headache.