라이브러리
[PHP] ArrayIterator::current - 현재 배열 항목을 반환합니다.
ArrayIterator::current()
PHP의 ArrayIterator는 이터레이터 인터페이스를 구현한 클래스로, 배열을 이터레이터로 변환하여 배열의 요소를 순회할 수 있도록 해줍니다. ArrayIterator::current() 메서드는 현재 이터레이터의 위치에 있는 요소를 반환합니다.
사용법
ArrayIterator::current() 메서드는 다음과 같이 사용할 수 있습니다.
#hostingforum.kr
php
$array = array('apple', 'banana', 'cherry');
$iterator = new ArrayIterator($array);
// 현재 위치에 있는 요소를 반환합니다.
$current = $iterator->current();
echo $current; // banana
// 현재 위치를 이동합니다.
$iterator->next();
// 현재 위치에 있는 요소를 반환합니다.
$current = $iterator->current();
echo $current; // cherry
예제
다음 예제에서는 ArrayIterator::current() 메서드를 사용하여 배열의 요소를 순회하며, 현재 위치에 있는 요소를 출력합니다.
#hostingforum.kr
php
$array = array(
'apple' => 'red',
'banana' => 'yellow',
'cherry' => 'red'
);
$iterator = new ArrayIterator($array);
while ($iterator->valid()) {
$current = $iterator->current();
echo "현재 위치에 있는 요소: $current
";
$iterator->next();
}
// 현재 위치에 있는 요소를 반환합니다.
$current = $iterator->current();
echo "마지막 위치에 있는 요소: $current";
참고
ArrayIterator::current() 메서드는 현재 이터레이터의 위치에 있는 요소를 반환합니다. 이터레이터의 위치는 next() 메서드를 호출하여 이동할 수 있습니다. ArrayIterator::current() 메서드는 null을 반환하는 경우가 있습니다. 예를 들어, 이터레이터의 위치가 처음 위치일 때는 null을 반환합니다.
#hostingforum.kr
php
$iterator = new ArrayIterator(array('apple', 'banana', 'cherry'));
echo $iterator->current(); // null
$iterator->next();
echo $iterator->current(); // apple
댓글목록
등록된 댓글이 없습니다.