Doc #75801 [Com]: Mistake in documentation example for null coalesce operator

From: Date: Thu, 11 Jan 2018 13:28:00 +0000
Subject: Doc #75801 [Com]: Mistake in documentation example for null coalesce operator
References: 1  Groups: php.doc.bugs 
Request: Send a blank email to doc-bugs+get-15329@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=75801&edit=1 ID: 75801 Comment by: pieter at frenssen dot be Reported by: pieter at frenssen dot be Summary: Mistake in documentation example for null coalesce operator Status: Open Type: Documentation Problem Package: Documentation problem PHP Version: Irrelevant Block user comment: N Private report: N New Comment: Actually the first suggestion is not correct, !empty() also returns TRUE if the value would be set to 0 or FALSE. So the second suggestion is the only correct one: isset($_POST['action']) && !is_null($_POST['action']). Previous Comments: ------------------------------------------------------------------------ [2018-01-11 13:23:28] pieter at frenssen dot be Description: ------------ --- From manual page: http://www.php.net/language.operators.comparison --- The example given for the null coalesce operator is not correct. This is the current example: <?php // Example usage for: Null Coalesce Operator $action = $_POST['action'] ?? 'default'; // The above is identical to this if/else statement if (isset($_POST['action'])) { $action = $_POST['action']; } else { $action = 'default'; } ?> It says that it is equivalent to using isset() in an if/else statement, but this is not true. If $_POST['action'] would be set with the value NULL then the first expression would assign the value default, but the second would assign the value NULL. In fact it is equivalent to using !empty(), so the example should be corrected to the following: <?php // Example usage for: Null Coalesce Operator $action = $_POST['action'] ?? 'default'; // The above is identical to this if/else statement if (!empty($_POST['action'])) { $action = $_POST['action']; } else { $action = 'default'; } ?> or possibly to the following, if we want to keep using isset() which is also mentioned elsewhere in the documentation: <?php // Example usage for: Null Coalesce Operator $action = $_POST['action'] ?? 'default'; // The above is identical to this if/else statement if (isset($_POST['action']) && !is_null($_POST['action'])) { $action = $_POST['action']; } else { $action = 'default'; } ?> ------------------------------------------------------------------------ -- Edit this bug report at https://bugs.php.net/bug.php?id=75801&edit=1

« previous php.doc.bugs (#15329) next »