Skip to content

Instantly share code, notes, and snippets.

@Linnk
Last active October 13, 2015 20:08
Show Gist options
  • Save Linnk/4248804 to your computer and use it in GitHub Desktop.
Save Linnk/4248804 to your computer and use it in GitHub Desktop.
Extending isset() and empty() functionality and the new is_recursively_set() for checking recursively an array with several keys of depth.
<?php
/**
* Usage:
*
* Instead of:
* if(isset($array['element1']) && isset($array['element2']) && isset($array['element3']) && isset($array['element4'] && isset($array['element5']))
*
* Use:
* if(is_set_in($array, 'element1', 'element2', 'element3', 'element4', 'element5'))
*
* Conclusion: Cleaner and legible.
* The function is_empty_in() also checks the value with empty() for each element.
*/
function is_set_in()
{
$args = func_get_args();
if(!isset($args[0]) || !isset($args[1]))
return null;
$array = array_shift($args);
foreach($args as $arg)
{
if(!isset($array[$arg]))
return false;
}
return true;
}
function is_not_set_in()
{
$args = func_get_args();
if(!isset($args[0]) || !isset($args[1]))
return null;
$array = array_shift($args);
foreach($args as $arg)
{
if(isset($array[$arg]))
return false;
}
return true;
}
function is_empty_in()
{
$args = func_get_args();
if(!isset($args[0]) || !isset($args[1]))
return null;
$array = array_shift($args);
foreach($args as $arg)
{
if(!isset($array[$arg]) || !empty($array[$arg]))
return false;
}
return true;
}
function is_not_empty_in()
{
$args = func_get_args();
if(!isset($args[0]) || !isset($args[1]))
return null;
$array = array_shift($args);
foreach($args as $arg)
{
if(!isset($array[$arg]) || empty($array[$arg]))
return false;
}
return true;
}
/**
* Usage of is_recursively_set($array, $keys = array()):
*
* Instead of:
* if(isset($array['element1']) && isset($array['element1']['element2']) && isset($array['element1']['element2']['element3']))
*
* Use:
* if(is_set_in($array, array('element1', 'element2', 'element3')))
*
* Conclusion: Again, cleaner and legible.
*/
function is_recursively_set($array, array $keys = array())
{
if(!is_array($array))
return true;
if(!isset($array[$keys[0]]))
return false;
$key = array_shift($keys);
return is_recursively_set($array[$key], $keys);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment