April 2011
2 posts
2 tags
PHP: removing zero values from an array
If you call array_filter without a callback function, it’ll remove all array elements that evaluate to false (including zeroes).
$numbers = array(0, 1, 2, 0);
echo array_filter($numbers);
Produces:
array(1,2);
2 tags
PHP: returning an array of single attributes from...
I miss Ruby’s shorthand collect method to return an array of single attributes:
animals.collect(&:name)
…so I’ve created a (less elegant) equivalent for PHP.
class ArrayExtensions
{
/**
* From an array of objects, create a new array containing only
* a single attribute of each object
*
* Similar to array.collect(&:attribute) in Ruby
*/
...