Anny
Anny

Reputation: 1

How could I fix this problem: in_array () expects parameter 2 to be array, null given in file... on line

I have a problem with this code. I get warning: in_array() expects parameter 2 to be array, null given in file... on line...

 /**
* Filter payment gateways
*/
function my_custom_available_payment_gateways( $gateways ) {
$chosen_shipping_rates = ( isset( WC()->session ) ) ? WC()->session->get( ‘chosen_shipping_methods’ ) : array();

if ( in_array( ‘flexible_shipping_6_1’, $chosen_shipping_rates ) ) :
unset( $gateways[‘cod’] );

elseif ( in_array( ‘flexible_shipping_6_4’, $chosen_shipping_rates ) ) :
unset( $gateways[‘bacs’] );
unset( $gateways[‘paypal’] );

endif;
return $gateways;
}
add_filter( ‘woocommerce_available_payment_gateways’, ‘my_custom_available_payment_gateways’ );

It will be nice if somebody can help me :-)

Upvotes: 0

Views: 994

Answers (2)

mondersky
mondersky

Reputation: 471

according to your code and supposing that $chosen_shipping_rates is sometimes not an array you can avoid the issue by making sure to execute the responsible code only if the variable is an array:

/**
* Filter payment gateways
*/
function my_custom_available_payment_gateways( $gateways ) {
    $chosen_shipping_rates = ( isset( WC()->session ) ) ? WC()->session->get( ‘chosen_shipping_methods’ ) : array();

    if(isset($chosen_shipping_rates) && is_array($chosen_shipping_rates )){
    if ( in_array( ‘flexible_shipping_6_1’, $chosen_shipping_rates ) ) :
    unset( $gateways[‘cod’] );
    elseif ( in_array( ‘flexible_shipping_6_4’, $chosen_shipping_rates ) ) :
    unset( $gateways[‘bacs’] );
    unset( $gateways[‘paypal’] );

    endif;
    }

return $gateways;
}

add_filter( ‘woocommerce_available_payment_gateways’, ‘my_custom_available_payment_gateways’ );

Upvotes: 1

dkutin
dkutin

Reputation: 31

Judging from your code, it could be that the $chosen_shipping_rates array hasn't been initialized and is resolving to NULL.

For example, if you were to do in_array('some string', $uninstantiated_array)

This will return the warning you are receiving.

My guess is that this is happening because WC()->session is set, but not WC()->session->get( ‘chosen_shipping_methods’ ) and thus you are getting a NULL array.

Try to see if adding a variable $chosen_shipping_methods = WC()->session->get( ‘chosen_shipping_methods’ ) and then using ( isset( $chosen_shipping_methods ) ) ? $chosen_shipping_methods : array(); to see if this solves your problem.

Upvotes: 1

Related Questions