Home > Back-end >  Getting Warning: array_push() expects parameter 1 to be array, string given /function.php
Getting Warning: array_push() expects parameter 1 to be array, string given /function.php

Time:11-18

I'm not so coding friendly, wasted almost 5 days to find a solution. Recently changed the hosting and then it started to happen. At the same time also got other warnings like

"Warning: Cannot modify header information - headers already sent by (output started at /var/www/u1524808/genericpanda.com/wp-content/themes/pillshope/functions.php:278) in /var/www/u1524808/genericpanda.com/wp-login.php on line 400"

and due to this I'm unable to log in to WordPress dashboard. Really facing a hard times. Here is the function where I'm getting the error. Really need help, Thank you in advance!!!

function register_my_session() {
    if (!session_id()) {
        session_start();
    }
    $_SESSION['cart']='';
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
       array_push($_SESSION['cart'], $_POST);
    }
}
add_action('init', 'register_my_session');

CodePudding user response:

You are using array_push but your $_SESSION['cart'] is a string because you initialize it as ' ' but instead you should do $_SESSION['cart'] = array()

CodePudding user response:

Two things

  1. output is already sent so no use of session_start() however if you want to add and by pass warning write it like

    @session_start()

  2. array_push($_SESSION['cart'], $_POST);

$_SESSION can be an array, $_SESSION['cart'] has empty string as you have assign it with empty quotes ('')

$_SESSION['cart'] = ''

so when you try to push data into $_SESSION['cart'] it gives you warning

You can either write $_SESSION['cart'] = [] and then your code works or

array_push($_SESSION['cart'], $_POST); 

can be

array_push($_SESSION, $_POST); 

but later part can wipe all other SESSON data so I suggest you should go with first alternative replace

$_SESSION['cart'] = '' 

with

$_SESSION['cart'] = [] 

and try.

  • Related