note 37680 added to control-structures.foreach

From: Date: Sun, 23 Nov 2003 02:42:22 +0000
Subject: note 37680 added to control-structures.foreach
Groups: php.notes 
Request: Send a blank email to php-notes+get-60848@lists.php.net to get a copy of this message
Note that foreach() will not return the key correctly if it contains a terminal zero ("\x00"). The key would get truncated. Consider the following: $test = array("A\x00B" => "Hello world"); foreach($test as $key => $value) { echo "$key = $value<br>"; } echo '$test["A"] = ' . $test["A"] . "<br>"; echo '$test["A\x00B"] = ' . $test["A\x00B"] . "<br>"; The output in PHP 4.3.2 is: A = Hello world $test_array["A"] = $test_array["A\x00B"] = Hello world The while(list(...) = each(...)) construction would yield the same result. In order to retrieve the correct key, you need to use array_keys(): $keys = array_keys($test); foreach($keys as $key) { $value = $test[$key]; echo "$key = $value<br>"; } ---- Manual Page -- http://www.php.net/manual/en/control-structures.foreach.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+37680 Delete -- http://master.php.net/manage/user-notes.php?action=delete+37680&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+37680&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#60848) next »