Why unset() doesn't work in PHP ternary operator

谁都会走 提交于 2020-07-19 05:05:52

问题


So there is a problem with this, but i'm blind to it. Even after reading the documentation twice (PHP Comparison Operators)

isset($items['blog']) ? unset($items['blog']) : NULL;

Parse error: syntax error, unexpected T_UNSET


回答1:


A @Bryan points out, no function calls to language constructs within the ternary operator. Since there's no return value involved at all here though, just do:

unset($items['blog']);

There's no need to check if the value is set or not beforehand. If it is not, unset simply won't do anything.




回答2:


You can't use unset inside of the ternary operation because it is not an expression that can be operated on. It's a language construct (like isset and echo) and can't be placed there.

Just use it and you're fine, no decision is needed:

unset($items['blog']);



回答3:


The error says, that T_UNSET (that is the tokenDocs for unset) is unexpected at that line. That means you can not place it there. That's all. Remove it and you're fine:

unset($items['blog']);

This has not much to do with the ternary operator btw., and as the code example shows, you don't need that operator for unset anyway.

If you love ternary operators very much, you can eval the unset:

isset($items['blog']) ? eval('unset($items[\'blog\'])') : NULL;

but that's not a serious suggestion because not very straight-forward.




回答4:


just a suggest regarding to benchmark matters : only use ternary syntax when you have to e.g in a view or if you really need one line code; therefore if else operator is much faster



来源:https://stackoverflow.com/questions/10475650/why-unset-doesnt-work-in-php-ternary-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!