I have code as following:
$arr1 = array();
$arr2 = array();
// [...] some code
$field_name = 'foo';
if (isset($arr1[$field_name])) {
$arr1[$field_name]++;
} else {
$arr1[$field_name] = 1;
}
$another_field_name = 'bar';
if (isset($arr2[$another_field_name])) {
$arr2[$another_field_name]++;
} else {
$arr2[$another_field_name] = 1;
}
There are many more arrays and the same ifelse
statements.
I would like to refactor these statements to a function:
function ifelse_arr ($arr_name, $field_name) {
if (isset($arr_name[$field_name])) {
$arr_name[$field_name]++;
} else {
$arr_name[$field_name] = 1;
}
}
But how can I pass an array name and field name as a variable to the function?
You don't want to pass array nor variable name, you want to pass array and variable themselves.
function ppIfIsset(array &$array, $field) {
$array[$field] = isset($array[$field]) ? $array[$field] + 1 : 1;
}
And call it like
ppIfIsset($arr1, 'foo');
Using & before function parameter, tells, that variable will be passed by reference
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments