-2

I still don't understand how to read this type checking with symbols ?? and only single ? and what's the difference. When i want to check the value of data, for an example i try this code:

//using double question mark
$course = isset($params->course_id) ?? NULL; //result that save in db is 0

//using single question mark
$course = isset($params->course_id) ? $params->course_id : NULL; //result that save in db is NULL

when i try to submit empty value the result is different, anybody can explain me?

chiper4
  • 303
  • 5
  • 18
  • The ternary operator, in `A ? B : C`, returns `B` as the value of the expression, when `A` is truthy, otherwise `C`. So with the second one, you are getting NULL, when `$params->course_id` is not set. – CBroe Dec 19 '22 at 08:26
  • Your first version is something completely different - if the result of `isset($params->course_id)` _was_ NULL, it would return NULL (due to the `??`.) But the result of that isset _is not_ NULL, it never is - it is either `true` or `false`. When `$params->course_id` is not set, `isset($params->course_id)` will get you `false`, which is not NULL - so `$course` contains `false` now. And when inserting into your DB, that gets converted to `0`. – CBroe Dec 19 '22 at 08:26

1 Answers1

2

The double question mark is the nullish-coaslescing operator and means - "If the value to my left is null or undefined... then return the content to my right"... (or perform the function to my right if thats what you have there)

The single question mark is part of a ternary operator and is paired with the colon symbol. The question mark evaluates to true and the colon to false (another way of thinking of this is the question mark is shorthand for an if block and the colon is shorthand for the else block

//using double question mark
$course = isset($params->course_id) ?? NULL; 

//means that is the preceding content is null or undefined - return NULL

//using single question mark the ? is the **if block**  and the : is the **else block** and then assigning that value to the course$ variable

$course = isset($params->course_id) 
  ? $params->course_id 
  : NULL; 
gavgrif
  • 15,194
  • 2
  • 25
  • 27
  • for nullish-coaslescing operator i set NULL for empty value, but value that stored in db is ```0```, why? – chiper4 Dec 19 '22 at 03:41