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 ...

5
  • Possible duplicate of stackoverflow.com/questions/6376702/php-unset-array-value Commented Jan 17, 2013 at 4:44
  • I don't follow your logic in what you were expecting. You unset a specific array key. Why would b=>c be gone? Commented Jan 17, 2013 at 4: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. Commented Jan 17, 2013 at 4: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. Commented Jan 17, 2013 at 4: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. Commented Jan 19, 2013 at 11:33

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

it does take by ref and more cause the data structure of php vars within its source may be more pointers than whats seen.
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().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.