1
votes

Why am I getting this error message "Warning: array_push() expects parameter 1 to be array, null given ..." When I removed the function and just run the for loop, it works, but not inside function. why?

<?php

$arr = array();
function callme() {
    for ($x = 1; $x <= 10; $x++) {
        array_push($arr, $x);
    }
    return $arr;
}

callme();

print_r($arr);

?>
3

3 Answers

1
votes

Declare array $arr as global

$arr = array();
function callme() {
    global $arr;
    for ($x = 1; $x <= 10; $x++) {
        array_push($arr, $x);
    }
    return $arr;
}

Or pass $arr as a parameter.

1
votes

You need to do either of two things:

Add $array as function parameter and return that.

<?php

$arr = array();
function callme($array) {
    for ($x = 1; $x <= 10; $x++) {
        array_push($array, $x);
    }
    return $array;
}

$arr = callme($arr);

print_r($arr);

?>

If you don't like returns you can have the array as reference...

<?php

$arr = array();
function callme(&$array) {
    for ($x = 1; $x <= 10; $x++) {
        array_push($array, $x);
    };
}

callme($arr);

print_r($arr);

?>

or define $arr als global in the function(least desired, you're stuck with only one array)

<?php

$arr = array();
function callme() {
    global $arr;
    for ($x = 1; $x <= 10; $x++) {
        array_push($arr, $x);
    }
    return $arr;
}

callme();

print_r($arr);

?>
0
votes

Someone needs to learn some basics about variable scopes.

http://php.net/manual/language.variables.scope.php