Reputation: 431
Is there a reason to use a string where an array will be required?
I have a developer who wants to pass a deliminated string, explode it in a database class method to pull out multiple field/value pairs from 2 separate strings. I can't think of a reason to not send in string arrays.
example:
$s = "value1|value2|value3" ;
$s2 = explode("|", $s);
vs an array
$s3 = array(
"1" => "value1",
"2" => "value2",
);
I know the idea is to actually pass an unknown number of key/value pairs but I don't think a string that you explode out is the answer. But I could be wrong.
Upvotes: 5
Views: 1479
Reputation: 198247
I can't think of a reason to not send in string arrays.
A string is a single entity. Your colleague uses the string "object" (an object in the sense of a variable or entity) to make it carry information, a very little form of a domains specific language that is.
But as it already shows, it's just overhead and not necessary. Probably that guy is just lazy to type and thinks that is more cool. What actually more cool is, is to just upgrade PHP and use the new array notation. It's short as well and it carries more information than a string which needs a parser (here explode with the separation character) first:
explode("|", "value1|value2|value3");
array("value1", "value2", "value3");
["value1", "value2", "value3"];
If you want an opinion how serious your colleague is: He is playing. Playing is okay, but if he needs to do power-play to show that he can suppress that as a style onto a shared codebase, slap onto his fingers. That's stupid. If you need an array, pass an array.
This is not something like let's say regular expressions. This is just some self-mockery of your colleague introducing problems into the codebase. Only because something is possible does not mean that it is better.
I can't think of a reason to not send in string arrays.
Well, some probable reasons I can imagine:
Please don't take these comments too seriously ;) It's okay you ask, but there is not much of an answer, because this smells fishy because there can be reasons that something like that can be useful (albeit I doubt that, because with some little OOP things start to look really differently here). So it always depends, but try to keep the code you edit simple to edit and don't add much magic. One could consider that string as a magic array.
Upvotes: 3
Reputation: 387
I'd say it's not enough information for 100% precise answer. In most cases the answer is no. But this may be some specific case.
Where from and where to do you pass the data?
Sometimes what you think of as an array is (or was) really actually a string, for example, if the "underlying" layer is JSON or XML. And it might be faster to pass and to parse the data by imploding/exploding strings -- but again, there is no common answer for this, it depends on many things, such as amount and structure of data. You should try and test it. Or provide more specific information :)
Upvotes: 0