note 114872 added to language.operators.comparison

From: Date: Fri, 18 Apr 2014 15:52:15 +0000
Subject: note 114872 added to language.operators.comparison
Groups: php.notes 
Request: Send a blank email to php-notes+get-199290@lists.php.net to get a copy of this message
I was interested about the following two uses of the ternary operator (PHP >= 5.3) for using a "default" value if a variable is not set or evaluates to false: <?php (isset($some_variable) && $some_variable) ? $some_variable : 'default_value'; $some_variable ?: 'default_value'; ?> The second is more readable, but will throw an ERR_NOTICE is $some_variable is not set. Of course, this could be overcome by suppressing the notice using the @ operator. Performance-wise, though, comparing 1 million iterations of the three statements (isset($foo) && $foo) ? $foo : '' ($foo) ?: '' (@$foo) ?: '' results in the following: $foo is NOT SET. [isset] 0.18222403526306 [?:] 0.57496404647827 [@ ?:] 0.64780592918396 $foo is NULL. [isset] 0.17995285987854 [?:] 0.15304207801819 [@ ?:] 0.20394206047058 $foo is FALSE. [isset] 0.19388508796692 [?:] 0.15359902381897 [@ ?:] 0.20741701126099 $foo is TRUE. [isset] 0.17265486717224 [?:] 0.11773896217346 [@ ?:] 0.16193103790283 In other words, using the long-form ternary operator with isset($some_variable) is preferable overall if $some_variable may not be set. (error_reporting was set to zero for the benchmark, to avoid printing a million notices...) ---- Server IP: 72.52.91.14 Probable Submitter: 86.26.19.176 ---- Manual Page -- http://php.net/manual/en/language.operators.comparison.php Edit -- https://master.php.net/note/edit/114872 Del: integrated -- https://master.php.net/note/delete/114872/integrated Del: useless -- https://master.php.net/note/delete/114872/useless Del: bad code -- https://master.php.net/note/delete/114872/bad+code Del: spam -- https://master.php.net/note/delete/114872/spam Del: non-english -- https://master.php.net/note/delete/114872/non-english Del: in docs -- https://master.php.net/note/delete/114872/in+docs Del: other reasons-- https://master.php.net/note/delete/114872 Reject -- https://master.php.net/note/reject/114872 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#199290) next »