목차
설명
supports iteration over three different kinds of values: arrays, normal objects, and traversable objects.
PHP에서 foreach 문은 배열의 원소나, 객체의 프로퍼티 수만큼 반복하여 동작하는 제어문(control)입니다.
foreach는 배열의 원소나, 객체의 프로퍼티에 값 하나하나에 대해 처리하는 경우에 for 문보다 깔끔한 코드를 만들어 낼 수 있습니다.
사용법
방법1 : Value만 가져오는 경우
foreach($array as $value)
방법2 : Key와 Value를 가져오는 경우
foreach($array as $key => $value)
예제1
코드
<?php
$employee_list = array(
'Programmer' => '이몽룡',
'Designer' => '성춘향'
);
foreach($employee_list as $row)
{
echo $row."<br/>";
}
?>
결과
이몽룡
성춘향
예제2
코드
<?php
$employee_list = array(
'Programmer' => '이몽룡',
'Designer' => '성춘향'
);
foreach($employee_list as $key => $value)
{
echo $key." : ".$value."<br/>";
}
?>
결과
Programmer : 이몽룡
Designer : 성춘향
[추가] list()로 중첩 배열 풀기 (since 5.5)
이중 배열을 순회하고 list()을 값으로 제공하여 이중 배열을 루프 변수로 꺼낼 수 있습니다.
전부꺼내는 법
<?php
$array = [
[1, 2],
[3, 4],
];
foreach ($array as list($a, $b)) {
// $a contains the first element of the nested array,
// and $b contains the second element.
echo "A: $a; B: $b\n";
}
?>
output
A: 1; B: 2
A: 3; B: 4
일부만 꺼내는 법
<?php
$array = [
[1, 2],
[3, 4],
];
foreach ($array as list($a)) {
// Note that there is no $b here.
echo "$a\n";
}
?>
output
1
3
에러가 날 수 있는 상황
<?php
$array = [
[1, 2],
[3, 4],
];
foreach ($array as list($a, $b, $c)) {
echo "A: $a; B: $b; C: $c\n";
}
?>
Notice: Undefined offset: 2 in example.php on line 7
A: 1; B: 2; C:
Notice: Undefined offset: 2 in example.php on line 7
A: 3; B: 4; C:
참고
'프로그래밍 언어(must-have skills) > PHP' 카테고리의 다른 글
php 벤치마크 사이트 추천 -The PHP Benchmark (0) | 2023.06.01 |
---|---|
__call method (0) | 2023.04.29 |
[라라벨] laravel-debugbar (0) | 2023.03.07 |
[Coding Standard(PSR-1)] PHP code MUST use only UTF-8 without BOM. (0) | 2023.02.11 |
versions of the PHP binary: TS(Tread-Safe) Vs NTS(Non-Tread-Safe) (0) | 2023.02.07 |