I have a file in PHP with a large array and a function that searches the array.
Heres the code:
$details = array(
array('fieldID'=>'0','fieldCaption'=>'Address 1','fieldType'=>'text','fieldName'=>'addr1','fieldRequired'=>'1'),
array('fieldID'=>'1','fieldCaption'=>'Address 2','fieldType'=>'text','fieldName'=>'addr2','fieldRequired'=>'1'),
.
.
.
);
if(!function_exists('find_detail'))
{
function find_detail($fieldName)
{
global $details;
var_dump($details); // NULL
foreach ($details as $detail)
{
if($detail['fieldName'] == $fieldName)
{
return $detail['fieldID'];
}
}
return false;
}
}
This sits inside a single helper file and calling var_dump($details); is returning NULL. I suspect an issue with scoping.
Many Thanks
-- edit --
This is bad practice and the best approach to handling this would be (as @Gordon stated) to pass the details array into the function. (Warning: There exist better ways of doing this, for example using array_filter)
if(!function_exists('find_detail_by_field_name'))
{
function find_detail_by_field_name($details, $fieldName)
{
foreach ($details as $detail)
{
if($detail['fieldName'] == $fieldName)
{
return $detail['fieldID'];
}
}
return false;
}
}
And provide a way to get the details, wrapping details in a function would provide many benefits such as caching, change of source etc.
function get_details()
{
static $details = array(...)
return $details;
}