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);
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);
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
*/
public static function collect_by_attribute($attribute, $array_of_objects)
{
if (!is_array($array_of_objects))
{
return array();
}
$output = array();
foreach ($array_of_objects as $object)
{
if (is_object($object) && isset($object->$attribute))
{
$output[] = $object->$attribute;
}
}
return $output;
}
}
Use it like this:
$colours = ArrayExtensions::collect_by_attribute('colour', $animals);
…and you’ll get a simple array containing just the attribute you’ve specified:
array('brown', 'blue', 'green')
If you happen to be using PHP ActiveRecord, they have a function called collect that will accomplish the same thing.
$colours = ActiveRecord\collect($animals, 'colour');
You can do this:
animals.collect(&:name)
…to return an array of animal names. This is essentially a shorthand version of:
animals.collect { |animal| animal.name }