0

Whenever I seek to show the contents of an array based on data from an SQL database, the output always is prefixed with the word "Array". It doesn't matter whether I use echo, print_r(), var_dump() or otherwise. Code below. Any ideas greatly received!

$prefix1 = ''; 
$tasks = array($product, $service, $order, $social, $competition, $dataOther);
foreach ($tasks as $task) {
    if ($task == '') {
        unset($task);
    } else {
        $tasks .= $prefix1 . '' . $task . '';
        $prefix1 = ', ';
    }
} 
echo $tasks;

Output - "Array" followed by the contents of $tasks

Edit: I cannot use implode(', ', $tasks) because each of the inputs (i.e. $product, $service etc.) could be blank and therefore the outcome would be ",," in places.

Hope that's clearer.

7
  • 1
    What do you want to do ??$tasks .= $prefix1 . '' . $task . ''; Commented Feb 10, 2017 at 12:34
  • 1
    You are overwriting your array in the loop, casting it to a string when you add a string to it. You should use a different name. Commented Feb 10, 2017 at 12:34
  • $tasks is an array or at least it was before you ran this code on it. You cannot echo an array Commented Feb 10, 2017 at 12:40
  • You cannot add to an array using .= Commented Feb 10, 2017 at 12:42
  • Basically this code makes very little sence! Fixing it would require more information about what your actual intent was! Commented Feb 10, 2017 at 12:43

1 Answer 1

4

You are overwriting your array in the loop, casting it to a string when you add a string to it. You should use a different name for the string you are building.

Although you don't really need a loop for this, you can replace your code with just:

$tasks = array($product, $service, $order, $social, $competition, $dataOther);
echo implode(', ', $tasks);

Edit: Based on your edit - that the variables can be blank - you can filter the empty values before you implode: array_filter without a callback function / second parameter removes empty values:

$tasks = array($product, $service, $order, $social, $competition, $dataOther);
echo implode(', ', array_filter($tasks));

Note that this will also filter strings like 0 so if that is not what you want, you would have to add a callback function that meets your requirements.

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

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.