note 109715 added to function.strlen

From: Date: Tue, 14 Aug 2012 03:59:40 +0000
Subject: note 109715 added to function.strlen
Groups: php.notes 
Request: Send a blank email to php-notes+get-190057@lists.php.net to get a copy of this message
I would like to demonstrate that you need more than just this function in order to truly test for an empty string. The reason being that <?php strlen(null); ?> will return 0. So how do you know if the value was null, or truly an empty string? <?php $foo = null; $len = strlen(null); $bar = ''; echo "Length: " . strlen($foo) . "<br>"; echo "Length: $len <br>"; echo "Length: " . strlen(null) . "<br>"; if (strlen($foo) === 0) echo 'Null length is Zero <br>'; if ($len === 0) echo 'Null length is still Zero <br>'; if (strlen($foo) == 0 && !is_null($foo)) echo '!is_null(): $foo is truly an empty string <br>'; else echo '!is_null(): $foo is probably null <br>'; if (strlen($foo) == 0 && isset($foo)) echo 'isset(): $foo is truly an empty string <br>'; else echo 'isset(): $foo is probably null <br>'; if (strlen($bar) == 0 && !is_null($bar)) echo '!is_null(): $bar is truly an empty string <br>'; else echo '!is_null(): $foo is probably null <br>'; if (strlen($bar) == 0 && isset($bar)) echo 'isset(): $bar is truly an empty string <br>'; else echo 'isset(): $foo is probably null <br>'; ?> // Begin Output: Length: 0 Length: 0 Length: 0 Null length is Zero Null length is still Zero !is_null(): $foo is probably null isset(): $foo is probably null !is_null(): $bar is truly an empty string isset(): $bar is truly an empty string // End Output So it would seem you need either is_null() or isset() in addition to strlen() if you care whether or not the original value was null. ---- Server IP: 69.147.83.197 Probable Submitter: 74.69.26.120 ---- Manual Page -- http://www.php.net/manual/en/function.strlen.php Edit -- https://master.php.net/note/edit/109715 Del: integrated -- https://master.php.net/note/delete/109715/integrated Del: useless -- https://master.php.net/note/delete/109715/useless Del: bad code -- https://master.php.net/note/delete/109715/bad+code Del: spam -- https://master.php.net/note/delete/109715/spam Del: non-english -- https://master.php.net/note/delete/109715/non-english Del: in docs -- https://master.php.net/note/delete/109715/in+docs Del: other reasons-- https://master.php.net/note/delete/109715 Reject -- https://master.php.net/note/reject/109715 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#190057) next »