Skip to content
Advertisement

What is better to use: in_array or array_unique?

I am in doubt what to use:

JavaScript

OR

JavaScript

UPDATE

The goal is to get array of unique values. This can be done by checking every time if value already exists with in_array or add all values each time and in the end use array_unique. So is there any major difference between this two ways?

Advertisement

Answer

I think the second approach would be more efficient. In fact, array_unique sorts the array then scans it.

Sorting is done in N log N steps, then scanning takes N steps.

The first approach takes N^2 steps (foreach element scans all N previous elements). On big arrays, there is a very big difference.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement