Forum und email

증가/감소 연산자

PHP는 C-스타일의 전처리와 후처리 증가/감소 연산자를 지원한다.

증가/감소 연산자
Example Name Effect
++$a Pre-increment Increments $a by one, then returns $a.
$a++ Post-increment Returns $a, then increments $a by one.
--$a Pre-decrement Decrements $a by one, then returns $a.
$a-- Post-decrement Returns $a, then decrements $a by one.

단순한 예제 스크립트:

<?php
echo "<h3>Postincrement</h3>";
$a 5;
echo 
"Should be 5: " $a++ . "<br />\n";
echo 
"Should be 6: " $a "<br />\n";

echo 
"<h3>Preincrement</h3>";
$a 5;
echo 
"Should be 6: " . ++$a "<br />\n";
echo 
"Should be 6: " $a "<br />\n";

echo 
"<h3>Postdecrement</h3>";
$a 5;
echo 
"Should be 5: " $a-- . "<br />\n";
echo 
"Should be 4: " $a "<br />\n";

echo 
"<h3>Predecrement</h3>";
$a 5;
echo 
"Should be 4: " . --$a "<br />\n";
echo 
"Should be 4: " $a "<br />\n";
?>

PHP는 문자 변수에 관한 산술 연산을 할때 C 방식이 아니라 펄 방식을 따른다. 예를 들면, 펄에서 'Z'+1은 'AA'를 전환되는 반면, C에서 'Z'+1은 '[' ( ord('Z') == 90, ord('[') == 91 )으로 전환된다. 문자 변수는 증가될수는 있으나 감소될수는 없다는 것에 주의해야 한다.

Example#1 문자 변수에 대한 산술 연산

<?php
$i 
'W';
for(
$n=0$n<6$n++)
  echo ++
$i "\n";

/*
  Produces the output similar to the following:

X
Y
Z
AA
AB
AC

*/
?>