Page 1 of 1

PHP implode query - why is this wrong?

Posted: Thu Jan 25, 2018 7:24 am
by simonmlewis
Hi there.
We are getting errors on the implode code.
Is the current version of PHP using this differently now??
Error is PHP Warning: implode(): Invalid arguments passed.

Code: Select all

add_action( 'woocommerce_after_shop_loop_item', 'bbloomer_echo_stock_variations_loop' );
 
function bbloomer_echo_stock_variations_loop(){
global $product;
    if ($product->get_type() == 'variable') {
        foreach ($product->get_available_variations() as $key) {
        $attr_string = '';
            foreach ( $key['attributes'] as $attr_name => $attr_value) {
                                $attr_string[] = $attr_value;
            }
            if ( $key['max_qty'] > 0 ) { echo '' . implode(', ', $attr_string) . ': ' . $key['max_qty'] .' in stock<br/>'; } else { echo '' . implode(', ', $attr_string) . ': out of stock<br/>'; }
            }
    }
}

Re: PHP implode query - why is this wrong?

Posted: Thu Jan 25, 2018 12:39 pm
by VladSun

Code: Select all

$attr_string = '';
and if there are no $key['attributes'] items then you have an error (implode expects as 2nd param an array, not a string).

Try instead:

Code: Select all

$attr_string = [];

Re: PHP implode query - why is this wrong?

Posted: Thu Jan 25, 2018 12:44 pm
by simonmlewis
Great thanks. Is it bad code or just old code?

Re: PHP implode query - why is this wrong?

Posted: Fri Jan 26, 2018 5:46 am
by VladSun
simonmlewis wrote:Great thanks. Is it bad code or just old code?
Bad code:
0) by design - usage of global in a function;
1) by design - mixing business logic and views;
2) by implementation - initializing a variable as a string and later implicitly casted and used as an array.
3) Code formatting?

Re: PHP implode query - why is this wrong?

Posted: Fri Jan 26, 2018 5:57 am
by simonmlewis
Wow - ok. It was taken from a website called Business Bloomer.