'Cookie values getting duplicated

Currently I have a searchbar that saves the users search query inside a cookie. To do this I'm saving all the users inputs inside an array. Now the problem is that if the user types the same thing again, it gets duplicated and saves the duplicate value in the array as well. I want a way where the duplicate value doesn't get added to the cookie that has been set:

$input_search = json_decode(($this->input->post('keyword_search')));

    if(isset($input_search))
    foreach($input_search as $searchvals){
        $searchvals->name = $searchvals->value;
        unset($searchvals->value);
        $searchval = json_encode($searchvals);

        if (!isset($_COOKIE['lpsearch_history'])){  
                setcookie('lpsearch_history',$searchval,time() +3600 *365,'/'); 
            }else {
                $locations[] = json_decode($_COOKIE['lpsearch_history'], true);
                $arrsearchval = json_decode($searchval, true);
                if(!in_array($arrsearchval, $locations))
                    $locations[] = $arrsearchval;
                $areas = json_encode($locations);
                setcookie('lpsearch_history',$areas,time() +3600 *365,'/');
            }
    }

Now this gives an output something like this:

[[[[{"type":"community","devslug":"downtown-dubai","name":"Downtown Dubai"}],
{"type":"community","devslug":"downtown-dubai","name":"Downtown Dubai"}],    
{"type":"community","devslug":"palm-jumeirah","name":"Palm Jumeirah"}],    
{"type":"community","devslug":"palm-jumeirah","name":"Palm Jumeirah"}]


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source