Delete a certain value from a comma-separated database field and reinsert again

Asked

Viewed 53 times

0

I need to delete a value from a comma-separated database field and reinsert again.

With the function str_replace PHP can delete all but the first or last one, because there is always a comma left. I am testing the function end PHP, more thank you 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.

  • Does that number come from a link? just a number or it comes like this 43,45 ?

  • A single string comes from the database field (all together) @rray

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 generate a comma-separated result string again:

$string = implode(",", $resultado); //45,46
  • 1

    Perfect @Filipe Moraes, thanks.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.