3

I've a multi-select attribute color.

$color = $_product->getAttributeText('color');
$output = implode(',', $color);
echo $output;

$color gives an array value. If there are multiple values present for the color attribute, say 1. blue and 2. green, it prints blue,green but when only one attribute is present for $color (say blue), it doesn't print any thing.

Is that the normal behaviour of implode? There must be multiple values present in array? If not then how I can print those single present values?

amitshree
  • 2,048
  • 2
  • 23
  • 41
  • 7
    No, this is not the normal behaviour of `implode()`. What is the output of: `print_r($color);` when you only receive one value ? – Rizier123 Jul 30 '15 at 13:46

3 Answers3

5

You can use is_array().

$color = $_product->getAttributeText('color');

if (is_array($color)) {
  $output = implode(',', $color);
} else {
  $output = $color;
}

echo $output;
Albzi
  • 15,431
  • 6
  • 46
  • 63
1

I am going to go out on a limb here, but I am going to guess that if there is one value returned it's a string; a string is invalid input for implode and will raise a PHP Warning.

In this case, implode will return a null value, which would explain why you are seeing nothing printed.

So ensure that you are passing an array to implode in all cases.

Edit

If you cannot see debug information in your development environment then you should consider setting your error_reporting() to help you debug your code. One simple way to do this is to add the following lines to the top of your script:

<?php

error_reporting(E_ALL|E_STRICT);
ini_set('display_errors', true);

// your code...

Note that you should not enable these settings in a production environment for security reasons.

Darragh Enright
  • 13,676
  • 7
  • 41
  • 48
0
Hello Dear,


    $color = 'blue';
    $output = implode(',', $color);
    echo $output;

It will give you a warning.

Warning: Invalid arguments passed.

But it works fine with array

    $color = array('blue');
    $output = implode(',', $color);
    echo $output;

Check the return value stored in `$color` and then go ahead.
Thanks.
Brn.Rajoriya
  • 1,534
  • 2
  • 23
  • 35