Posts Tagged ‘arrays’
The Zend Framework is teaching me PHP Tricks!
Just a “quickpress” – Loving the new WordPress Admin btw – great job!
I’ve been writing PHP for a while and am a big hater of people who do not check their arrays are arrays before doing a foreach, and have their error reporting settings so high that they don’t notice the warning it generates when it fails.
Having read though some of the Zend Framework code I came across a way to rid yourself of the is_array() and and if(count($myArray) > 0) checks before a foreach loop. It doesn’t totally solve the problem, but it will remove the “invalid arguments supplied for foreach loop” warning message we see.
Now if you’re sure you’ll be getting an array to deal with then there’s no real need for this. It’s more useable in the context of when you are unsure weather you will be getting a string or an array into your foreach loop.
Anyway, enough of this gay banter…here’s the code.
foreach ( (array) $returnColumns as $returnColumn) {
if (in_array($returnColumn, $availableColumns)) {
$returnObject->{$returnColumn} = $this->_resultRow[$returnColumn];
}
}
That’s from the Zend_Auth class. It’s so cool though. In this particular function it accepts a string or an array as an arguement, this way we ensure foreach always has an array to deal with! Supercool trick if you ask me, and just to illustrate it a little further here’s somethignI made earlier:
$mystring = "abcdefg"; $array = (array) $mystring; print_r($array); // outputs // Array // ( // [0] => abcdefg // )
Yeah I know its nothing groundbreaking but, you learn something new everyday!