I have got a couple of functions that manipulate data in an array, for example unset_data() you pass it the value and an unlimited amount of string args like:
unset_data( $my_array, "firstname", "password" );
and it can handle multi-dimentional arrays etc, quite simple.
But should this function use a reference to the array and change it directly?
Or should i return the new array with the values unset.
I can never decide whether a function should use reference or not,
Is there like, specific cases or examples when and when to not use them??
Thanks
I'd ask myself what the expected use case of the function is. Does the typical use case involve keeping the original data intact and deriving new data from it, or is the explicit use case of this function to modify data in place?
Say md5 would modify data in place, that would be pretty inconvenient, since I usually want to keep the original data intact. So I'd always have to do this:
$hash = $data;
md5($hash);
instead of:
$hash = md5($data);
That's pretty ugly code, forced on you by the API of the function.
For unset though, I don't think the typical use case is for deriving new data:
$arr = unset($arr['foo']);
That seems pretty clunky as well as possibly a performance hit.
Generally speaking, it's better to return by value instead of taking a reference because:
array_filter(unset_data(...))Most of the time, these advantages come at the cost of using up additional memory. Unless you have good reason (or better yet, proof) to believe that the additional memory consumption is going to be an issue, my advice is to just return the mutated value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With