PHP: combine a full array with an empty array or check isset ()?

I have several functions that an array must return so that it merges with another array.

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

  • Returns an empty array and combines it with a full OR
  • Return zero, save the return in a variable, check this variable, and THEN merge it if necessary.

I ask this because sometimes the shortest route is not the fastest, and I really don't know what array_merge () does under the hood.

+4
source share
3 answers

Returns an empty array. Compare the complexity of the two options.

  • Returns an empty array and combines it with a full OR
  • Return zero, save the return in a variable, check this variable, and THEN merge it if necessary.

When you write a function, people other than you will use it (this includes you from the 6-month move, which has no idea what you are doing now). If you return null, someone using your function should be aware that it may not return an array, so anytime they use your function, then you need to wrap the variables in many is_array or is_set . This leads to difficult maintenance of the code in the future or to errors when it works, when your application / system works, when the array is returned, but not when null is returned. If your function always returns an array, people can safely pass it to functions that expect an array. (this is why some proponents of strong type coercion hate PHP. In a language like Java, this is not good, because functions have a certain type of thing to return)

Your attention to performance is commendable, but in general, the built-in array manipulation functions are pretty well tuned, and they will only be a bottleneck of a small percentage of the time. In the daily work of the code, the efficiency of work with checking the value of variables and merging in an array of zero elements will be insignificant.

Go through the Cleaner API, check and then optimize specific cases when you start to see a performance problem.

+4
source

If nothing is returned, return only an empty array. It sounds the most logical.

+1
source

I would go ...

  • Returns an empty array if nothing happens wrong

  • Returns false (or throws an exception) if an error occurs

... since this will mean that you need to do a little extra work, this is probably the best practice and will pay dividends in the long run. (array_merging with the return value may look neat, but it is a bit dubious if there is no possibility of any errors.)

+1
source

Source: https://habr.com/ru/post/1299041/


All Articles