$c is not always $a["c"]
Today I was tipped off to a certain quirk of PHP, specifically with how it handles Array resources. Every programmer knows, (or should know), the differences between creating a new copy of a variable and making a new reference to the same variable. In PHP, as far as I’ve known, you never access memory directly. Thus, trying $v = "hello"; $a = &$v; $b = &$a; does not make the value of $b a byte pointer to the location of $a, but instead a new reference to what $v holds. So, modifying $b means you will implicitly edit $v. To those familiar with PHP, this is understandable and often both acceptable and helpful. (As lazy programmers, we don’t want to have to remember when we have a reference or an ‘original’ copy of a value.)
What I didn’t know, is that this could get us into a lot of trouble without even expecting it. The problem occurs whenever you try to obtain a reference to an element in a PHP array. Case in point:
$a=Array("one"=>1, "two"=>2,"three"=>null);
$b = $a["four"];
$c =& $a["five"];
What do we get if we print the value of $a variables? $a is now
$a = Array( ["a"] => 1, ["b"] => 2, ["d"] => null, ["c"] => &null )
WHAT?! What happened to $b? What in the world is a pointer to null? PHP actually created the “c” key within my Array, just by referencing it in a read context. Lesson learned: always use isset($a["key"]) before attempting to draw from an Array by reference!
About this entry
You’re currently reading “$c is not always $a["c"],” an entry on Advent Digerati
- Published:
- Thursday, April 2nd, 2009 at 5:42 PM
- Author:
- Zack
- Category:
- PHP
- Tags:
- Code Snippet
No comments
Jump to comment form | comments rss | trackback uri