note 51603 added to language.types.array

From: Date: Tue, 05 Apr 2005 15:24:09 +0000
Subject: note 51603 added to language.types.array
Groups: php.notes 
Request: Send a blank email to php-notes+get-87500@lists.php.net to get a copy of this message
Something that tripped me up: If you mix string and integer keys, be careful if you are doing a comparison on the to find if a string key exists. For example, this will not do what you expect it to do: <?php $exampleArray = array(); $exampleArray['foo'] = 'bar'; $exampleArray[] = 'Will create 0 index'; $keyWeAreLookingFor = "correctKey"; foreach ($exampleArray as $key => $value){ if ($key == $keyWeAreLookingFor){ print "Found Key"; } } ?> It will print "Found Key", because (I presume) when PHP makes the comparison between the string "correctKey" and the index 0, it casts the string to an integer, rather than casting 0 to the string "0" and then doing the comparison. Using === fixes the problem: <?php foreach ($exampleArray as $key => $value){ if ($key === $keyWeAreLookingFor){ print "Found Key"; } } ?> ---- Manual Page -- http://www.php.net/manual/en/language.types.array.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+51603 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+51603&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+51603&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+51603&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+51603&report=yes&reason=useless Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+51603&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+51603&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#87500) next »