1

I came across some PHP behavior that I think is subtle, but pretty cool. But I don't understand how...

$test=array('a'=>'c', 'b'=>'c');
unset($test['a']);
var_dump($test);

This prints

array(1) { ["b"]=> string(1) "c" }

I would have expected the array to be emptied out. After all, $test['a'] evaluates to 'c' so the unset function only sees 'c' but knows it was just the first 'c' value I wanted removing?

My guess is the interpeter is super smart and looks inside the array inside the parameter given to it - but that's purely conjecture ...

nchaud
  • 377
  • 3
  • 13
  • Possible duplicate of http://stackoverflow.com/questions/6376702/php-unset-array-value – rink.attendant.6 Jan 17 '13 at 04:44
  • I don't follow your logic in what you were expecting. You unset a specific array key. Why would `b=>c` be gone? – Brad Jan 17 '13 at 04:45
  • @Brad OP expected that PHP first interprets `$test['a']` which hold the value of `'c'` and then performs a removal of ALL identical values. – Ja͢ck Jan 17 '13 at 04:46
  • @Jack, Oh, that makes sense! I understand now. I think I've been looking at PHP too long when stuff like that makes sense. – Brad Jan 17 '13 at 04:46
  • @rink.attendant.6, I did actually look at that question before posting (thanks to SO's helpful feature of showing related questing when you start typing) but no-one explained the WHY - but Kolink below's made it clear now - of course, just use pass by ref. – nchaud Jan 19 '13 at 11:33

2 Answers2

1

Erm, no. unset is not a function, it is a language construct. Therefore it doesn't necessarily follow the same rules.

In this case, however, it actually works similarly to a pass-by-reference. It takes the reference to the variable, and destroys it.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • it does take by ref and more cause the data structure of php vars within its source may be more pointers than whats seen. – thevikas Jan 17 '13 at 12:52
0

What you're actually doing is destroying (unsetting) the key "a" from the array $test. So after that key is destroyed, only "b" exists in the array.

If you wanted to remove all values of 'c' from the array, use array_diff().

rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156