How do I add elements to an array only if they aren\'t in there already? I have the following:
$a=array();
// organize the array
foreach($array as $k=>$v)
With array_flip() it could look like this:
$flipped = array_flip($opts);
$flipped[$newValue] = 1;
$opts = array_keys($flipped);
With array_unique() - like this:
$opts[] = $newValue;
$opts = array_values(array_unique($opts));
Notice that array_values(...) — you need it if you're exporting array to JavaScript in JSON form. array_unique() alone would simply unset duplicate keys, without rebuilding the remaining elements'. So, after converting to JSON this would produce object, instead of array.
>>> json_encode(array_unique(['a','b','b','c']))
=> "{"0":"a","1":"b","3":"c"}"
>>> json_encode(array_values(array_unique(['a','b','b','c'])))
=> "["a","b","c"]"