Hello, I have this code and I want to correct it because it deletes all same value and I want to delete one value
$rows = "944,1001,1001,3946";
$sesto = explode(",",$rows);
$arr = array_diff($sesto,array(1001));
$comma_separated = implode(",", $arr);
echo $comma_separated;
i want to be 944,1001,3946
You can use array_search to find the index of the first match and then use array_splice to remove it:
$rows = "944,1001,1001,3946";
$arr = explode(",",$rows);
array_splice($arr, array_search(1001, $arr), 1);
$comma_separated = implode(",", $arr);
echo $comma_separated;
Note that this assumes that the element exists in the array. If you try to delete an element that doesn't exist it will delete the first element instead. If you do not want that behaviour use this to make sure it found an element before deleting:
$rows = "944,1001,1001,3946";
$arr = explode(",",$rows);
$index = array_search(1001, $arr);
if ( $index !== false )
array_splice($arr, $index, 1);
$comma_separated = implode(",", $arr);
echo $comma_separated;
for simplicity array_unique($sesto)
for more info https://www.w3resource.com/php/function-reference/array_unique.php
Hope this helps.
You're asking how to remove a value from an array, but it looks like you really need to remove it from a string. You start with a string, then turn it back into a string at the end before output. If that's really the situation, you can use preg_replace
to remove the value directly from the string without converting back and forth to array.
$value = 1001;
$rows = preg_replace("/\b{$value},|,{$value}$/", '', $rows, 1);
echo $rows;
I'm not a regex expert, so there's probably a better way to write the regex, but this works for your example, and the general idea is the same even if the specific regex can be optimized.
The last argument limits the replacements to 1.