PHP - Add value to comma based string/array

5.7k views Asked by At

I am storing some data in my database in a comma based string like this:

value1, value2, value3, value4 etc...

This is the variables for the string:

$data["subscribers"];

I have a function which on users request can remove their value from the string or add it.

This is how I remove it:

    /* Remove value from comma seperated string */
    function removeFromString($str, $item) {
    $parts = explode(',', $str);

    while(($i = array_search($item, $parts)) !== false) {
        unset($parts[$i]);
    }

    return implode(',', $parts);
    }
    $newString = removeFromString($existArr, $userdata["id"]);

So in the above example, I am removing the $userdata['id'] from the string (if it exists).

My problem is.. how can I add a value to the comma based string?

3

There are 3 answers

0
Nelson Owalo On BEST ANSWER

You can use $array[] = $var; simply do:

function addtoString($str, $item) {
    $parts = explode(',', $str);
    $parts[] = $item;

    return implode(',', $parts);
    }
    $newString = addtoString($existArr, $userdata["id"]);
3
Eduardo Escobar On
function addToString($str, $item) {
    $parts = explode(',', $str);
    array_push($parts, $str);
    return implode(',', $parts);
}
$newString = addToString($existArr, $userdata["id"]);
0
David Mchedlishvili On

Best performance for me

function addItem($str, $item) {
    return ($str != '' ? $str.',' : '').$item;
}