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;
}
If your function operates on that
$detailsarray, it should ask for that array in the function signature. Anything else is just hiding dependencies and is hard to debug and maintain (as you can see by the need to ask your question). So change it toand foreach over the passed in array then.
Also, since the function really returns the fieldId and not some detail, you might want to rename it to
But to answer your question: you likely get this effect because you created the $details array outside the global scope, the topmost scope of your script. If you defined $details in a function or a method or if it is included in the scope of another function, it is not in the global scope.