'Best way to check if variable is set and can be 'foreach'ed
I've taken over a larger code base, that has several warnings and errors.
I keep running into statements like this:
foreach( $object->keys => $key ){
...
}
Where I can see in the error log, that $object is null.
What is the simplest way, tot check that above-written statement won't break?
To be 100% sure, I would do something like this:
if( isset( $object ) && is_array( $object->keys ) ){
foreach( $object->keys => $key ){
...
}
}
But the readability decreases significantly.
I could also make a helper function, that did it, like so:
if( myHelper::canBeForeached( $object, 'keys' ) ){ // naming would obviously be changed
foreach( $object->keys => $key ){
...
}
}
But that too seems bad.
What is the simplest/prettiest way to achieve this, to also maintain readability of the code?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
