March 22, 2012

Errors when using array_push — "First argument should be an array"

Question by Nate

I have the following code:

<?php

function foo($bar) 
{
    global $products; 

    //$products = array();

    $query = 'SELECT p_name FROM 0_products WHERE p_category IN (' . $bar . ')';
    $results = mysql_query($query);

    while($row = mysql_fetch_array($results, MYSQL_ASSOC))
    {
        array_push($products, $row);
        echo 'name pushed, ';
    }
}

require('mysql_ipb_connect.php'); // connect to ipb mysql database

$products = array(); 
foo(5);

?>

When I run it I get the following output:

Warning: array_push() [function.array-push]: First argument should be an array in /home/rgcpanel/public_html/category/category.php on line 14
name pushed,
Warning: array_push() [function.array-push]: First argument should be an array in /home/rgcpanel/public_html/category/category.php on line 14
name pushed,
Warning: array_push() [function.array-push]: First argument should be an array in /home/rgcpanel/public_html/category/category.php on line 14
name pushed, 

If I uncomment “$products = array();” then the output is correct:

name pushed, name pushed, name pushed, 

Why is this happening? I declare the $products array outside of a function (so it’s global), and then specify it as being a global inside the function. Something is not right, but I’m not sure what that is?

Thanks for your advice.

Answer by Michael Berkowski

Per the comments, $products was initialized by an included file which was included inside a function. That defines its scope to the function, rather than globally. So you’ll need to use global $products; before calling the include.

function func_that_defined_products() {
  global $products;
  include('file_that_defines_products.php');
}

// Now when called globally later, it will be at the correct scope.


function foo($bar) 
{
    global $products; 
    $query = 'SELECT p_name FROM 0_products WHERE p_category IN (' . $bar . ')';
    // etc...
}

In any case, I find it a little more readable to use $GLOBALS['products'] instead of the global keyword. And as always, wherever possible it is a preferred practice to pass the variable into a function rather than accessing it globally.

// If you can, do it this way
function foo($bar, $products) {
  // $products was a param, and so global is unnecessary
}

However in your case, if the CMS defines it you may lose the flexibility to do it that way…

Answer by Starx

Uncomment this part

//$products = array();

Initialise the $products as an array

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!