How can i put "if" inside array in php?
mean:
return [
'cars' => [
'test' => $arrayTest,
'test1' => $arrayTest1,
],
'session' => [
'sessionkey' => "$xyz",
'lastlogintime' => $sess,
if ($xyzp->available > 0){
'availablenow' => true;
} else{
'wait' => '7_days_waiting';
]
];
problem is propably in using "=>"
Thanks
3
Answers
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.
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:Put the array in a variable, then use an
if
statement to add the conditional keys and values.If the key were constant and you had both an
if
andelse
value for it, you could have used a ternary in the value of that key.Use the ternary operator – as suggested in the other answers for the value – also for the key:
Or: