mcjordalini mcjordalini - 5 months ago 6
PHP Question

PHP: When an associative array is within a function, and the function is called more than once, does it create the array multiple times?

So I have a function called vendorGet() and it contains an array of vendor names and their logos. I call the vendorGet() function in another array and pass it a string argument to tell it which vendor to output from the array of vendors. Does doing this cause the PHP script to create this array every time the function is called, or does it create it once within the function and reference itself each time?

Hope that made sense. Let me know if there is anything I can clarify.
Here is some (shortened down and simplified) code as a reference,

// Vendor Fetcher
function vendorGet($data)
{
$vendor = array(
'foo' => array(
'name' => 'Foo Products',
'image' => (VENDOR_IMG . 'foo/foo-logo.png'),
),
'bar' => array( // ABT
'name' => 'Bar Inc.',
'image' => (VENDOR_IMG . 'bar/bar-logo.png'),
),
);

return $vendor[$data];
}

// Array calling vendorGet() function
$catalogue = array(
'chapter-1' => array(
'vendors' => array(
1 => vendorGet('foo'),
2 => vendorGet('bar'),
),
),
);

Answer

In short, the array will be set up every time the function is called because you're defining it within the function

If you want to avoid this you can use a class

class vendor {

   public static $vendor = array(
       'foo' => array(
         'name' => 'Foo Products',
         'image' => (VENDOR_IMG . 'foo/foo-logo.png'),
       ),
       'bar' => array( // ABT
         'name' => 'Bar Inc.',
         'image' => (VENDOR_IMG . 'bar/bar-logo.png'),
       ),
    );


    public static function get($data) {
         return self::$vendor[$data];
    }
}