This is tested against PHP 7.4 I’m trying to understand why the first example does not return ‘hello’ like the other two. Example 3 is the same thing as example 1 except the ternary is encapsulated in parentheses but for some reason the presence of the parentheses on example 3 give the expected result. Example 2 is the same as
Tag: null-coalescing-operator
Is there a fancy and short solution for using the null coalescing operator with constants in PHP?
Since PHP 8 the constant() function throws an error instead of returning null and generating an E_WARNING when the given constant is not defined, and therefore I can’t use the following code to set a variable anymore: My obvious quick solution for this is changing that line to: It honestly bothers me a little because I like how the first
PHP: is there a good syntax to initialize an array element depending on whether it is undefined or not, without using if?
The double question mark syntax in PHP will return null if $bar is undefined. This syntax is extremely useful to simplify code and avoid massive if statements. Now I have the following situation It seems so likely that there exists a one-line simplification for the statement but I just couldn’t come up with it. The closest I come up with
How to display a column of data when the parent variable might not be declared?
I am generating some dynamic content in the view layer of my codeigniter project. The trouble is, I am getting the following error in my ternary expression: Parse error: syntax error, unexpected token “foreach” How can I display the looped category_name data separated by <br/> tags without generating this error when $log->category is not declared? Answer The code you have
Right associativity of PHP’s null coalesce operator
According to PHP documentation, the null coalescing operator ?? is right-associative, i.e. is equivalent to What is the significance of this? Does it make any difference for developers that it is left-associative or right-associative? To those who are thinking it will call less functions, this is not true because the right operand will not be evaluated if the left operand