Delete a certain value in a database field separated by commas and reinsert

0

I need to delete a value from a database field separated by commas and re-enter again.

With PHP's str_replace function, I can delete all but the first or last, since there is always a comma left over. I'm testing the end function of PHP, but I appreciate any solution.

$referenciaDel; // 44 

$referencia; // 44,45,46

$replace = str_replace(",".$referenciaDel,"",$referencia); 

If it is the first value to be deleted it does not work because I added the comma in the function, and the first value has no comma before.

    
asked by anonymous 08.04.2016 / 15:21

1 answer

2

You can convert your string into an array and remove the specific value.

//Converte a string em um array. Nesse caso o delimitador é a vírgula
$array = explode(",", $referencia); //[44,45,46]

//Adiciona em um array todos os números que serão removidos
$paraRemover = array($referenciaDel); //[44]

//Retorna apenas os itens que não são comuns entre os arrays
$resultado = array_diff($array, $paraRemover); //[45,46]

To regenerate a comma-separated result string:

$string = implode(",", $resultado); //45,46
    
08.04.2016 / 15:35