phparraysarray-unique

What is better to use: in_array or array_unique?


I am in doubt what to use:

foreach(){
    // .....

    if(!in_array($view, $this->_views[$condition]))
        array_push($this->_views[$condition], $view);

    // ....
}

OR

foreach(){
    // .....

    array_push($this->_views[$condition], $view);

    // ....
}

$this->_views[$condition] = array_unique($this->_views[$condition]);

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?


Solution

  • 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.