开发者

PHP: Merge full array with empty array or check isset() first?

I have a few functions that should return an arra开发者_开发问答y, to have it merged with another array.

However, sometimes there's nothing to return. What's the best scenario here?

  1. Return an empty array and merge that with the full one OR
  2. Return null, store the return in a variable, check that variable and THEN merge it if needed.

I'm asking this because sometimes the shortest route isn't the fastest, and I don't really know what array_merge() does under the hood.


Return the empty array. Compare the complexity of your two options

  1. Return an empty array and merge that with the full one OR
  2. Return null, store the return in a variable, check that variable and THEN merge it if needed.

When you write a function, people other than you are going to use it (this includes the you from 6 month forward who has no idea what current you is doing). If you return null, someone using your function needs to know it might not return an array, so anytime they use your function then need to wrap their variables in a lot of is_array or is_set checks. This leads to harder to maintain code down the road, or bugs where it works when your app/system works when an array is returned, but not when a null is returned. If your function always returns an array, people can safely pass it to functions expecting an array. (this is why some advocates of strong type enforcement hate PHP. In a language like Java this doesn't happy because functions have return a specific type of thing)

You attention to performance is laudable, but in general the built in array manipulation functions are pretty well tuned, and are only going to bottleneck a small percentage of the time. In day to day code running, the performance benefits of checking the value of the variables and merging in a zero element array are going to be negligible.

Go with the cleaner API, benchmark, and then optimize specific cases where you start seeing a performance problem.


If there is nothing to return, return just an empty array. It sounds most logically.


I'd go for...

  1. Return an empty array if nothing went wrong

  2. Return false (or throw an exception) if an error occurred

...as whilst this will mean that you have to do a bit of extra work, it's probably better practice and will pay dividends in the long run. (array_merging with the return value might look neat, but it's a bit dubious unless there's no possibility of any errors occurring.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜