Warning: array_push() expects parameter 1 to be array

喜欢而已 提交于 2019-12-03 04:42:27

In the scope in which array_push() is called, $printed was never initialized. Either declare it as global or include it in the function parameters:

$printed = array();
.
.
.
function dayAdvance ($startDay, $endDay, $weekType){
    global $printed;
    .
    .
    .
}

OR

function dayAdvance ($startDay, $endDay, $weekType, $printed = array()) { ... }

NOTE:

A faster alternative to array_push() is to simply append values to your array using []:

$printed[] = $newdateform;

This method will automatically detect if the variable was never initialized, and convert it to an array prior to appending the data (in other words, no error).

UPDATE:

If you want the value of $printed to persist outside of the function, you must either pass it by reference or declare it as global. The above examples are NOT equivalent. The following example would be equivalent to using global (and is, in fact, a better practice than using global - it forces you to be more deliberate with your code, preventing accidental data manipulation):

function dayAdvance ($startDay, $endDay, $weekType, &$printed) { ... }

You need to use global $printed; or to add $printed as a function parameter.

You may also pass the $printed parameter as reference in your function: http://php.net/manual/en/language.references.pass.php

More about global and variable scopes: http://php.net/manual/en/language.variables.scope.php

Instead of the function array_push() use $your_array[] = $element_to_be_added; when you want to add a single element to the array.

As mentioned in the docs, this creates a new array, if the array is null:

Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.

and:

Note: array_push() will raise a warning if the first argument is not an array. This differs from the $var[] behaviour where a new array is created.

from: http://php.net/manual/en/function.array-push.php

You need validate whit is_array:

Example

if (is_array($arNumbers)) {
    $cellid =  array_push($arNumbers, 0);
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!