Reputation: 1908
I have following function
function getSum($array){
if(is_array($array)) {
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$sum = 0;
foreach ($iterator as $key => $value) {
$sum += $value;
}
} else{
$sum = $array;
}
return $sum;
}
And I'm using it like this
$teams = array();
$teams[1]['AREA I']['blue'] = 30;
$teams[1]['AREA I']['green'] = 25;
$teams[1]['AREA II']['blue'] = 15;
$teams[2]['AREA I']['blue'] = 40;
echo getSum($teams); //output: 110
echo getSum($teams[1]); //output: 70
echo getSum($teams[1]['AREA I']); //output: 55
echo getSum($teams[1]['AREA I']['blue']); //output: 30
How to avoid error Undefined offset when using like getSum($teams[2]['AREA IV']
(key AREA IV not set)? In this case I want that function returns zero.
Upvotes: 0
Views: 294
Reputation: 350760
Since the error occurs before the getSum function is called, there is no way you can change that function so that it would work.
However, if you are willing to change the arguments that are passed to getSum, you could get around that. You could pass the array without further keys specifications (to avoid the potential error) and specify the key(s) as a second argument. Then leave it to getSum to try to get to that value if it exists, like this:
function getSum($array, $path = array()){
// process second argument:
foreach ($path as $key) {
if (!is_array($array) || !isset($array[$key])) {
return 0; // key does not exist, return 0
}
$array = $array[$key];
}
if(is_array($array)) {
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$sum = 0;
foreach ($iterator as $key => $value) {
$sum += $value;
}
} else{
$sum = $array;
}
return $sum;
}
$teams = array();
$teams[1]['AREA I']['blue'] = 30;
$teams[1]['AREA I']['green'] = 25;
$teams[1]['AREA II']['blue'] = 15;
$teams[2]['AREA I']['blue'] = 40;
// pass an optional 2nd argument:
echo getSum($teams); //output: 110
echo getSum($teams, [1]); //output: 70
echo getSum($teams, [1,'AREA I']); //output: 55
echo getSum($teams, [1,'AREA I','blue']); //output: 30
echo getSum($teams, [2, 'AREA IV']); // no error, output: 0
Upvotes: 1