Skip to content

Instantly share code, notes, and snippets.

@tondol
Last active August 29, 2015 14:02
Show Gist options
  • Save tondol/8d767a2541bf39451a83 to your computer and use it in GitHub Desktop.
Save tondol/8d767a2541bf39451a83 to your computer and use it in GitHub Desktop.
PHPのNoticeを消すのに便利な奴
// 第1引数に配列もしくはオブジェクトを,
// 第2引数以降に配列のキー名もしくはプロパティ名を与える
// 指定した要素やプロパティが存在しなければNULLが返却される
function array_at()
{
$numargs = func_num_args();
$args = func_get_args();
$arr = array_shift($args);
foreach ($args as $index) {
if (is_array($arr)) {
$arr = isset($arr[$index]) ? $arr[$index] : null;
} else if (is_object($arr)) {
$arr = isset($arr->{$index}) ? $arr->{$index} : null;
}
}
return $arr;
}
// nullの代わりにデフォルト値を与えられるようにしたもの
// 引数の最後にデフォルト値を与える
function array_at_default()
{
$numargs = func_num_args();
$args = func_get_args();
$arr = array_shift($args);
$default = array_pop($args);
foreach ($args as $index) {
if (is_array($arr)) {
$arr = isset($arr[$index]) ? $arr[$index] : $default;
} else if (is_object($arr)) {
$arr = isset($arr->{$index}) ? $arr->{$index} : $default;
}
}
return $arr;
}
@tondol
Copy link
Author

tondol commented Jun 9, 2014

使い方

  • array_at($_POST, 'values', 0); // $_POST['values'][0]
  • array_at_default($object, 'property1', 'property2', ''); // $object->property1->property2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment