Lumikko Posted July 31, 2011 Share Posted July 31, 2011 Hello Here is the problem: I have this example string: $string = "Product 1, Product 2, Product 3, Product 4, Product 5, Product 6, Product 7, Product 8, Product 9, Product 10, Product 11, Product 12, Product 13"; Now i wan't to check if string has multiple same names (or numbers) and to be cleaned using array_unique function. First, those products will be stripped to "tags" with this function: function split_tags($string) { $array = preg_split("/[\s]*[, ][\s]*/", $string); while(list($key,$val)=each($array)){ if($val<>" " and strlen($val) > 0){ $tag .= "$val, "; } } $tag=substr($tag,0,(strLen($tag)-2)); return $tag; } So the $string will looks like this: Product, 1, Product, 2, Product, 3, Product, 4, Product, 5, Product, 6, Product, 7, Product, 8, Product, 9, Product, 10, Product, 11, Product, 12, Product, 13" Then this function should do the "magic": function unique_tags($array) { $array = implode(',',array_unique(explode(',', $array))); return $array; Here is desired output: Product, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 But my script give's this output: Product, 1, Product, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 So it almost works. I also tryed to change $string to this (see: , before Product 1): [code]$string = ", Product 1, Product 2, Product 3, Product 4, Product 5, Product 6, Product 7, Product 8, Product 9, Product 10, Product 11, Product 12, Product 13"; [/code] But it don't do anything. Quote Link to comment https://forums.phpfreaks.com/topic/243392-problem-with-array_unique-function/ Share on other sites More sharing options...
@ Posted August 5, 2011 Share Posted August 5, 2011 hmm i think you will find that one of the 'Product' values has a leaded or trailing space which is why you get Product, 1, Product, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 not sure how to fix your functions but if you are interested the below will give you the result you are after: $string = "Product 1, Product 2, Product 3, Product 4, Product 5, Product 6, Product 7, Product 8, Product 9, Product 10, Product 11, Product 12, Product 13"; preg_match_all('/(?<=, ).*?(?= [0-9])|^.*?(?= [0-9])|([0-9].*?(?=,))/', $string, $matches); $uniqueValues = implode(',', array_unique(array_values($matches[0]))); print_r($uniqueValues); Quote Link to comment https://forums.phpfreaks.com/topic/243392-problem-with-array_unique-function/#findComment-1252555 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.