I access an API that returns an array of elements.
If there is only one element, it will return the array as:
Array {
[response] => Array {
[name] => Frank
}
}
However, if there are multiple results, it goes one level deeper to account for each result:
Array {
[response] => Array {
[0] = > Array {
[name] => Frank
}
[1] = > Array {
[name] => John
}
}
}
This is quite frustrating as it means I have to first check if there is just one element or more than one, and then code each one separately.
Is there a better solution that automatically takes care of both scenarios (e.g. one result vs. multiple results) and always retrieves the name’s that are available regardless ?
You could either write an iterator that would deal with your special case, or you iterate over it an deal with the special case:
Special cases can be very annoying, so take care of them early and ideally make them disappear.