for, foreach 함수 정보
for, foreach 함수본문
for, foreach함수가 다른 함수에 비해 햇갈려서 정리 해봤습니다.
# PHP for 함수
* for loop는 몇번을 실행할지를 미리 아는경우에 사용한다.
(The for loop is used when you know in advance how many times the script should run.)
*문법
for (init counter; test counter; increment counter) {
code to be executed;
}
- init counter: 루프카운터 값을 초기화한다.
- test counter: 각각 실행되는 루프값을 평가한다.
실행되는 값이 참이면 계속 루프를 돌리고, 거짓이면 루프를 끝낸다.
- increment counter: 루프카운터 값을 증가시킨다.
* 예: 초기값에 0을 주고 10보다 작거나 같으면 실행하고 결과를 출력하는 for문
<?php
for ($x=0; $x<=10; $x++) {
echo "The number is: $x <br>";
}
?>
결과:
The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
The number is: 10
# foreach loop: foreach loop는 오직 array에서만 작동하며, array안에서 각각의 key/value 쌍으로 작동한다.
각각의 루프마다 current array의 value값을 $value에 할당한다. 그러면 array pointer가 하나씩 이동하면서 마지막 array element까지 루프한다.
* 문법
foreach ($array as $value) {
code to be executed;
}
* 예: array의 각각 칼라값을 $value에 하나씩 넣고 $value를 출력한다.
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
echo "$value <br>";
}
?>
-결과
red
green
blue
yellow
0
댓글 7개
복잡하고 어려우면 for문이 좋은거같더라구요^^
애용해야겠습니다
포...
거의 고정이라면 포이치..