PHP - array_push() expects parameter 1 to be array, null given

PHP - array_push() expects parameter 1 to be array, null given

winstonwinston Member
edited August 2012 in Help

`$arrMessages = array();

function AddMessage($strMsg) { global $arrMessages;

array_push($arrMessages, $strMsg); }`

When calling AddMessage further down in the code I get array_push() expects parameter 1 to be array, null given

I'm absolutely dumbfounded by this....please help :(!

EDIT: Weirdest thing I've ever seen, I need to define it as a global before defining it as an array, and then define the global again inside the function....

Comments

  • Why not just use $arrMessages[] = $strMsg;

    BitAccel - OpenVZ VPS / IRC,VPN,Anything Legal & Unrivaled Support!
    Thanked by 1joepie91
  • telephonetelephone Member
    edited August 2012

    Think of a function as a sandbox. You need to define the input variables you're going to be using, or as you mentioned use global (which is not advised!).

    $arrMessages = array();
    
    function AddMessage($array, $msg)
    {
        return array_push($array, $msg);
    }
    
    Or you can typecast:
    
    function AddMessage(array $array, $msg)
    {
        return array_push($array, $msg);
    }
    
    Or as Corey mentioned:
    
    $arrMessages[] = $strMsg;
  • @Corey said: Why not just use $arrMessages[] = $strMsg;

    Agreed. Even the PHP docs say to use this method instead of array_push.

  • @NickM said: Agreed. Even the PHP docs say to use this method instead of array_push.

    From PHP Docs ->

    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. 
    
    BitAccel - OpenVZ VPS / IRC,VPN,Anything Legal & Unrivaled Support!
    Thanked by 1joepie91
  • changed it to $arrMessages[] = $strMsg;

    thanks!

Sign In or Register to comment.