I have a function which returns a referenced value by default – however, the function should return false if something went wrong during processing things in the function.
The function is declared as follows.
function &find($idx, $pref_array = false) {
if ($pref_array === false)
$pref_array = &$this->preferences;
foreach ($pref_array as $key => $data) {
if ($key == $idx) {
return $pref_array[$idx];
}
else if (is_array($data)) {
$res = &$this->find($idx, &$pref_array[$key]);
if ($res !== false)
return $res;
}
}
return false;
}
PHP gives me a notice that “Only variable references should be returned by reference”. Do I really need to put $result = false; in my code and return $result? That would be somehow ridiculous.
Thanks in advance for your help.
I think that that is not a good way to code a general find function because it would be impossible to determine if a
FALSEvalue returned from the function means that the value of the searched item was in factFALSEor if the searched item was not found.If you know that
FALSEare not legal values than its OK, otherwise you should implement the find function in a different way.For example this way:
This way you can always know if the requested item was found by checking the value returned from the function and if the returned value is TRUE you would have a reference to the found item in the variable referenced by the
$found_valueargument.Finally, this way you don’t get any strange notice 😉