Skip to content

Instantly share code, notes, and snippets.

@tomsseisums
Last active December 16, 2015 05:48
Show Gist options
  • Save tomsseisums/5386737 to your computer and use it in GitHub Desktop.
Save tomsseisums/5386737 to your computer and use it in GitHub Desktop.
Smart helpers for PHP
<?php
function is(&$variable, $filters)
{
$filters = explode('|', $filters);
$state = false;
foreach ($filters as $filter)
{
switch ($filter)
{
case 'filled':
$state = !empty($variable);
break;
case 'array':
$state = is_array($variable);
break;
}
if ($state === false) break;
}
return $state;
}
$a = array(4);
var_dump(
is($a, 'filled|array'), // true
is($b, 'filled|array') // false (notice, that $b is not even defined, yet there is no notice)
);
<?php
// Global flags to be used all around the new methods
define('ITERATOR_EMPTY', 1);
define('ITERATOR_INT', 2);
// Flag resolver
function get_flag_methods($flags)
{
$functions = array();
if ($flags & ITERATOR_EMPTY) $functions[] = function ($value){ return empty($value); };
if ($flags & ITERATOR_INT) $functions[] = function ($value){ return !is_int($value); };
return $functions;
}
// foreach with filters
function all(array $elements, callable $callback, $flags = 0)
{
$methods = get_flag_methods($flags);
foreach ($elements as $index => $element)
{
foreach ($methods as $test)
{
if (call_user_func($test, $element) ) continue 2;
}
$callback($index, $element);
}
}
// test
all(array('', 5, 'lol', 22), function ($key, $value) {
echo $value . '<br>';
}, ITERATOR_EMPTY | ITERATOR_INT);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment