0

I have multi-dimensional array like this:

Array
(
    [0] => Array
        (
            [id] => 10184            
            [user_tags] => tag1
         )
)

how do i add more 'user_tags' with comma seperated in an array using php

Thanks

2
  • How do i add more tags like this eg,tag1,tag2,tag3.... Commented Mar 8, 2011 at 8:45
  • 1
    What should the result be? Do you want more array entries or just set user_tags to this comma-separated list? Commented Mar 8, 2011 at 8:48

3 Answers 3

3
 $arr[0]['user_tag'] .= ','.$valueToAdd;

or

$arr[0]['user_tag'] .= ','.implode(',', $valueToAdd); // if its an array
Sign up to request clarification or add additional context in comments.

Comments

3

You can add something to your 'user_tags' like this :

$myarray[0]['user_tags'] = 'whatever';

If you have an array of tags like this, you can add it like that :

$tags = array('tag1', 'tag2', 'tag3', 'tag4');
$myarray[0]['user_tags'] = implode(', ', $tags);

But in this case, it is maybe better to store the array directly like said in another comment.

If you want to just add one tag :

$myarray[0]['user_tags'] .= ', '.$mytag;

Comments

2

As a hint, I wouldn't store the usertags in comma separated style, but rather in another array, so that $myArray['user_tags'] = array('tag1, 'tag2', 'tag3', ...);.

You can then translate between array and csv like this:

$myArray['user_tags_csv'] = implode(',', $myArray['user_tags']);
$myArray['user_tags'] = explode(',', $myArray['user_tags_csv']);

This makes it easier to search the tags for existing ones before you append one.

I use this a lot (esp. with user tags or flags) in connection with an SQL database. With different separators (e.g. ',' ';' '|') I even create hierarchical csv strings which translate into multi-dimensional arrays.

Pro-tip: Store the tags in an associative array like {'tag1'='tag1', 'tag2'='tag2'}, create it with

$myArray['user_tags'] = array_combine(explode(',', $myArray['user_tags_csv']), explode(',', $myArray['user_tags_csv']);

Then you can use array_key_exists() as well as array_search() and many other neat things. I use that a lot.

Comments

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.