note 87868 added to function.strpos

From: Date: Sun, 28 Dec 2008 00:48:04 +0000
Subject: note 87868 added to function.strpos
Groups: php.notes 
Request: Send a blank email to php-notes+get-148594@lists.php.net to get a copy of this message
The Situation: I wanted to return TRUE if strpos returned position 0, and only position 0, without the added overhead of preg_match. The Solution: As PHP treats 0 (zero) as NULL, and strpos returns the int 0 (but not NULL), I used type casting and the "===" comparison operator (as it compares types) to resolve my issue. <?php $hayStack = "dbHost"; $needle = "db" $needlePos = strpos($hayStack, $needle); if((string)$needlePos === (string)0) { echo "db is in position zero"; } else { echo "db is NOT in position zero"; } ?> Returns: db is in position zero <?php $hayStack = "another_db_host"; $needle = "db" $needlePos = strpos($hayStack, $needle); if((string)$needlePos === (string)0) { echo "db is in position zero"; } else { echo "db is NOT in position zero"; } ?> This returns: db is in NOT position zero ---- Server IP: 69.147.83.197 Probable Submitter: 71.233.5.86 ---- Manual Page -- http://www.php.net/manual/en/function.strpos.php Edit -- https://master.php.net/note/edit/87868 Del: integrated -- https://master.php.net/note/delete/87868/integrated Del: useless -- https://master.php.net/note/delete/87868/useless Del: bad code -- https://master.php.net/note/delete/87868/bad+code Del: spam -- https://master.php.net/note/delete/87868/spam Del: non-english -- https://master.php.net/note/delete/87868/non-english Del: in docs -- https://master.php.net/note/delete/87868/in+docs Del: other reasons-- https://master.php.net/note/delete/87868 Reject -- https://master.php.net/note/reject/87868 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#148594) next »