Delete duplicate values of a variable in php


In a varibale I have the repeated values

$variable= "1,2,3,4,5,6,7,8,9,1,2,3,4,8,9,1,2,3";

there is some php functionality that allows to eliminate the repeated values =

I did the test with array_unique($variable); but I get a mistake when I take the test

asked by Norbey Martinez 28.02.2018 в 18:06

3 answers


We convert the string to array with explode and then pass the array to array_unique I leave you with an example:

$variable= '1,2,3,4,5,6,7,8,9,1,2,3,4,8,9,1,2,3';    
$a_val = explode(',',$variable);
$a_result = array_unique($a_val);

The variable $ a_result would be array without duplicates. If you want to pass the array again to a string you use the implode method, I'll give you the example:

$varible  = implode(",",$a_result);
answered by 28.02.2018 в 18:22

Assuming that parts of a string that consists of numbers separated by commas, you should do the following:

1-Convert the string into an array with the function explode which is responsible for converting a string in array given a delimiter, in this case the comma:

 $variable= "1,2,3,4,5,6,7,8,9,1,2,3,4,8,9,1,2,3";
 $array = explode(",",$variable);

2- Eliminate the repeated values of the array with the function array_unique :


3-Re-convert the array in string with the function implode that converts an array in string separated by the given delimiter:





answered by 28.02.2018 в 18:20

First you must convert it into an array since the array_unique expects as input the information in data type array

$variable= "1,2,3,4,5,6,7,8,9,1,2,3,4,8,9,1,2,3";
$variable= = explode(",", $variable);

So later you can apply as well you mention the array_unique($variable);

answered by 28.02.2018 в 18:21