Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 848
user1692333 Avatar asked Apr 10 '13 21:04

user1692333


People also ask

What is Array_unique?

The array_unique() function removes duplicate values from an array. If two or more array values are the same, the first appearance will be kept and the other will be removed. Note: The returned array will keep the first array item's key type.

How can I get unique values from two arrays in PHP?

The array_diff() (manual) function can be used to find the difference between two arrays: $array1 = array(10, 20, 40, 80); $array2 = array(10, 20, 100, 200); $diff = array_diff($array1, $array2); // $diff = array(40, 80, 100, 200);

How to unique an array in PHP?

The array_unique() is a built-in function in PHP and this function removes duplicate values from an array. If there are multiple elements in the array with same values then the first appearing element will be kept and all other occurrences of this element will be removed from the array.


2 Answers

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.

like image 90
p91paul Avatar answered Sep 19 '22 17:09

p91paul


Honestly if you're using a small dataset it does not matter which one you use. If your dataset is in the 10000s you'll most definitely want to use a hash map for this sort of thing.

This is assuming the views are a string or something, which it looks like it is. This is typically O(n) and possibly the fastest way to deal with tracking unique values.

foreach($views as $view)
{
    if(!array_key_exists($view,$unique_views))
    {
        $unique_views[$condition][$view] = true;
    }
}
like image 45
Anther Avatar answered Sep 20 '22 17:09

Anther