0

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?

5
  • 1
    Maybe it's just me, but I find it quite surprising that you can come up with the logic for removeFromString but is unable to do so for addToString. Commented Jun 21, 2015 at 15:26
  • @light I like how you think :-0 Commented Jun 21, 2015 at 15:31
  • 1
    This really isn't a good idea.... storing comma-separated values in a database always causes so many problems for people Commented Jun 21, 2015 at 16:09
  • @MarkBaker what kind Of problems? Commented Jun 21, 2015 at 17:19
  • 1
    Precisely the problems you're having: adding, modifying and deleting values from the set..... not to mention searching for records that have a specific value among the set of comma-separated values in that column (find me all the records that user 3 subscribes to) Commented Jun 21, 2015 at 17:48

3 Answers 3

3

Best performance for me

function addItem($str, $item) {
    return ($str != '' ? $str.',' : '').$item;
}
Sign up to request clarification or add additional context in comments.

Comments

2

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

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

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

Comments

1
function addToString($str, $item) {
    $parts = explode(',', $str);
    array_push($parts, $str);
    return implode(',', $parts);
}
$newString = addToString($existArr, $userdata["id"]);

3 Comments

The function name should be addToString
Cool, from the version i proposed, just a minor change is needed to be done
Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.