You can't add control structures inside of an array assignment. You'd have to use an array for the partial result, and then add the keys conditionally afterwards.
$res = [
'cars' => [
'test' => $arrayTest,
'test1' => $arrayTest1,
],
'session' => [
'sessionkey' => "$xyz",
'lastlogintime' => $sess,
]
];
if ($xyzp->available > 0){
$res['availablenow'] => true;
} else{
$res['wait'] => '7_days_waiting';
}
return $res;
The other suggestions in the comments about using a ternary would work, but not necessarily cleanly since you're setting different keys based on the conditional. Using the ternary both keys would exist in the resulting array, but the "other" key would be set to NULL or another "not set" value of your choosing. Eg:
return [
'cars' => [
'test' => $arrayTest,
'test1' => $arrayTest1,
],
'session' => [
'sessionkey' => "$xyz",
'lastlogintime' => $sess,
'availablenow' => ($xyzp->available > 0) ? true : false,
'wait' => ($xyzp->available > 0) ? NULL : '7_days_waiting'
]
];
Edit: lukas.j's answer has a "clean output" solution with just ternaries, but it also demonstrates the pitfall of ternaries where it becomes difficult to tell what multiple ternaries in a row are actually doing.
IMO for ternaries [and all code, really] there's a judgement call to be made between, "I want my code to be compact" and "I want my code to be easily readable".
($xyzp->available > 0 ? 'availablenow' : 'wait') => ($xyzp->available > 0 ? true : '7_days_waiting'), ...but it's a bit tortuous. Much easier to do what you want in two steps - ie initialise your array, then do your conditional expression to modify it.