Last active
December 13, 2018 02:37
-
-
Save ytkhs/388cc9451212980b1175751a2a2caa6b to your computer and use it in GitHub Desktop.
配列の最初or最後のキーを取り出す(PHP7.3) ref: https://qiita.com/ytkhs/items/6b97d0f46d3a04ef5183
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$arr = ['a' => 'Alice', 'b' => 'Bob']; | |
# 今まで(ポインタが移動しちゃう) | |
end($arr); | |
# => "Bob" | |
# 存在チェックが必要なのでこれはこれで長い。いい方法あるかな? | |
$lastkey = array_key_last($arr); | |
array_key_exists($lastkey, $arr) ? $arr[$lastkey] : null | |
# => "Bob" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$arr = ['a' => 'Alice', 'b' => 'Bob']; | |
# わざわざポインタを動かしてから取得しないといけない | |
reset($arr); | |
key($arr); | |
# => "a" | |
end($arr); | |
key($arr); | |
# => "b" | |
# わざわざキーだけの配列を生成してから取得。しかも作った配列$keysを破壊する | |
$keys = array_keys($arr); | |
array_shift($keys); | |
# => "a" | |
$keys = array_keys($arr); | |
array_pop($keys); | |
# => "b" | |
# 呼ぶたびに変わっていく... | |
array_pop($keys); | |
# => "a" | |
array_pop($keys); | |
# => null | |
# 強引に一行でやろうとするとE_NOTICEをだす | |
reset(array_keys($arr)); | |
# => PHP Notice: Only variables should be passed by reference... |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$arr = ['a' => 'Alice', 'b' => 'Bob']; | |
array_key_first($arr); | |
# => "a" | |
array_key_last($arr); | |
# => "b" | |
# 何回呼んでもOK | |
array_key_last($arr); | |
# => "b" | |
# ちなみに空配列の場合はNULLです | |
array_key_last([]); | |
# => null |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment