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’t use file_exists because it doesn’t search the include path.
fopen has a third argument that will check the include path, though:
if (@fopen('Log.php', 'r', true))
{
echo 'It exists!';
}
if(!preg_match('/^(\d{4})-((0[1-9])|(1[0-2]))-(0[1-9]|[12][0-9]|3[01])$/', $date)) {
throw new sfException('Date must be in yyyy-mm-dd format');
}
The commonly used
$this->getRequestParameter('blah')
is a shortened version of
$this->getRequest()->getRequestParameter('blah')
All sorts of other goodies are available using $this->getRequest(), including for example:
$this->getRequest()->getPathInfo()
$moduleName = sfContext::getInstance()->getModuleName();
Use the letter i after the ending delimiter. For example:
preg_match("/^TMG-[A-Z]-([0-9]+)/i",$itemNumber)
The solution is to use session_set_cookie_params() to allow any subdomain to access the session:
session_set_cookie_params (86400,'','.yourdomain.co.uk');
session_start();
Note the dot before the domain name. session_set_cookie_params() must be called before session_start(), and must be called on every request.
The SQL parser in PHPMyAdmin 2.6.x (the version used in Plesk 7.5) falls over when confronted with an ISNULL query, for example:
SELECT ISNULL(id) FROM user
The bug is fixed in recent versions of PMA (2.9.x works fine).