0

I am looking to store the database values which are already stored as id's and retrieve via a for each loop within an array.

I have tried something like this, but it is not working:

foreach ($list as $item)
{
     $commaSeparated = implode(',' , $item['id');
}
echo $commaSeparated;

Where item['id'] is the specific column pulled out of the query. If I use the $list variable, then I am getting the full result of the query which I do not want.

But, my error results in this:

Warning: implode(): Invalid arguments passed 

This is what has correctly returned what I need:

foreach ($list as &$id)
        {

            $listArr[] = $id['toolbar_id'];

            $commaSeparated = implode(',' , $listArr)

                             echo $commaSeparated;

5 Answers 5

2

That happens because you need to perform

$commaSeparated = implode(',' , $list);

It is not a good practice though. You should never store the lists as comma-separated items in database. Instead - create additional table for it and store 1 item per row.

Sign up to request clarification or add additional context in comments.

3 Comments

I miscommunicated my issue. The items are coming from the database already. They are single id values. I am trying to store each one of these values which are pulled from a query into an array. Although if I use $list as the value to store in the array, it does not pull the specific column value as I would want. I will edit my question above.
@Brandon Ellis: you need to rephrase your question obviously then
Yes. I just have. My apologies.
2

The second argument to implode needs to be an array. Try this:

$commaSeparated = implode(',', $list);

Comments

2

Implode function accepts a separator and an array for parameters. Then you should do this:

$commaSeparated = implode(',' , $list);

echo $commaSeparated;

(Source: http://php.net/manual/pt_BR/function.implode.php)

Comments

0

You need to do more checks to avoid the error if your data is not in correct format.

if(is_array($list)){
    foreach ($list as $item)
    {
        if(is_array($item)) 
            $commaSeparated = implode(',' , $item);
    }
    echo $commaSeparated;
}

Comments

0

I suggest you trying a var_dump($variable) where $variable is the ...variable, in which the data is stored, knowing its structure will tell you what data to expect and how to iterate over it.

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.