I have a attribute of a class that needs to be checked. The variable is a string but I want to convert it to an array if it is not empty, or else return an empty array.
'myVariable' => $token->getUser()->getRecord()->getLevel() ?: []
As of now, if getLevel() returns something, it returns as a string, but I want an array. Is there a way to do this while keeping the ?: operator.
If I understand your question correctly, this should do it for you:
'myVariable' => [$token->getUser()->getRecord()->getLevel()]
If getLevel()
returns a string, you'll end up with an array containing that one string. If getLevel()
returns nothing, you'll end up with an empty array.
Edit: Check that, you'll end up with an array that contains a NULL element. If that won't work for you, you can try this version, which will give you an array with zero elements:
'myVariable' => (array) $token->getUser()->getRecord()->getLevel() ?: []
you can try
'myVariable' => ($token->getUser()->getRecord()->getLevel()!="") ?explode(",",$token->getUser()->getRecord()->getLevel()):array()