Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
608 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...