Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
599 views
in Technique[技术] by (71.8m points)

array_push() expects parameter 1 to be array, null given php error message

I'm trying to save some values from a variable into my session array with php.

Here is my code:

    <?php 
session_start();
if (session_status() == PHP_SESSION_NONE) {
    $_SESSION['messages'] = array();  
}
$request_params = array();
if (isset($_POST['send'])){
    $pm = $_POST['message'];
    array_push($_SESSION['messages'], $pm); 
    $request_params = [
        'chat_id' => $id,
        'text' => implode(" ", $_SESSION['messages'])
    ];
    echo $_SESSION['messages'];
    print_r($request_params);
}
?>
<div class="box-footer">
    <form action="" method="post">
        <div class="input-group">
            <input type="text" name="message" placeholder="Write your direct message" class="form-control">
            <span class="input-group-btn">
                <input name="send" type="submit" class="btn btn-danger btn-flat"/>
            </span>
        </div>
    </form>
</div>

And these are the errors that appear when I try to submit the form:

Warning: array_push() expects parameter 1 to be array, null given in new.php on line 9

Warning: implode(): Invalid arguments passed in new.php on line 12

Line 9:

array_push($_SESSION['messages'], $pm);

And line 12:

'text' => implode(" ", $_SESSION['messages'])

So how to solve these issues ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You get the error : Warning: array_push() expects parameter 1 to be array, null given

because your $_SESSION['messages'] variable is never set.

When this part of your code gets executed,

session_start();
if (session_status() == PHP_SESSION_NONE) {
    $_SESSION['messages'] = array();  
}

The first line starts a new session. So session_status() == PHP_SESSION_NONE will never be true since session_status() returns 2 and PHP_SESSION_NONE equals to 1. As a result, $_SESSION['messages'] = array(); will not get executed.

What you need to be doing is, check if a session has been started, and start one if not.

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

This will check if you have a session_start() called somewhere earlier in your script.

Then after that, add this line:

if(!isset($_SESSION['messages']))
    $_SESSION['messages'] = array();

Hope it helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...