cvs: phpdoc /en/language control-structures.xml /en/language/control-structures alternative-syntax.xml break.xml continue.xml declare.xml
do-while.xml else.xml elseif.xml for.xml foreach.xml if.xml include-once.xml include.xml require-once.xml require.xml return.xml switch.xml while.xml

From: Date: Sat, 27 Dec 2008 01:35:49 +0000
Subject: cvs: phpdoc /en/language control-structures.xml /en/language/control-structures alternative-syntax.xml break.xml continue.xml declare.xml
do-while.xml else.xml elseif.xml for.xml foreach.xml if.xml include-once.xml include.xml require-once.xml require.xml return.xml switch.xml while.xml
Groups: php.doc.cvs 
Request: Send a blank email to doc-cvs+get-2838@lists.php.net to get a copy of this message
philip Sat Dec 27 01:35:49 2008 UTC Added files: /phpdoc/en/language/control-structures alternative-syntax.xml break.xml continue.xml declare.xml do-while.xml else.xml elseif.xml for.xml foreach.xml if.xml include-once.xml include.xml require-once.xml require.xml return.xml switch.xml while.xml Modified files: /phpdoc/en/language control-structures.xml Log: - Split control-structures.xml into control-structures/*.xml - No content was changed - Whitespace has been changed - Changed to utf-8 - The history of these files can be viewed here: --- http://cvs.php.net/viewvc.cgi/phpdoc/en/language/control-structures.xml?annotate=1.173

http://cvs.php.net/viewvc.cgi/phpdoc/en/language/control-structures.xml?r1=1.173&r2=1.174&diff_format=u Index: phpdoc/en/language/control-structures.xml diff -u phpdoc/en/language/control-structures.xml:1.173 phpdoc/en/language/control-structures.xml:1.174 --- phpdoc/en/language/control-structures.xml:1.173 Thu Nov 27 10:19:08 2008 +++ phpdoc/en/language/control-structures.xml Sat Dec 27 01:35:49 2008 @@ -1,1903 +1,41 @@ -<?xml version="1.0" encoding="iso-8859-1"?> -<!-- $Revision: 1.173 $ --> - <chapter xml:id="language.control-structures" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink"> - <title>Control Structures</title> - - <sect1 xml:id="control-structures.intro"> - <title>Introduction</title> - <simpara> - Any PHP script is built out of a series of statements. A statement - can be an assignment, a function call, a loop, a conditional - statement or even a statement that does nothing (an empty - statement). Statements usually end with a semicolon. In addition, - statements can be grouped into a statement-group by encapsulating a - group of statements with curly braces. A statement-group is a - statement by itself as well. The various statement types are - described in this chapter. - </simpara> - </sect1> - - <sect1 xml:id="control-structures.if"> - <title><literal>if</literal></title> - <para> - The <literal>if</literal> construct is one of the most important - features of many languages, PHP included. It allows for - conditional execution of code fragments. PHP features an - <literal>if</literal> structure that is similar to that of C: - <informalexample> - <programlisting> -<![CDATA[ -if (expr) - statement -]]> - </programlisting> - </informalexample> - </para> - <simpara> - As described in <link linkend="language.expressions">the section about - expressions</link>, <replaceable>expression</replaceable> is evaluated to its - Boolean value. If <replaceable>expression</replaceable> evaluates to &true;, - PHP will execute <replaceable>statement</replaceable>, and if it evaluates - to &false; - it'll ignore it. More information about what values evaluate - to &false; can be found in the <link - linkend="language.types.boolean.casting">'Converting to boolean'</link> - section. - </simpara> - <para> - The following example would display <computeroutput>a is bigger - than b</computeroutput> if <varname>$a</varname> is bigger - than <varname>$b</varname>: - <informalexample> - <programlisting role="php"> -<![CDATA[ -<?php -if ($a > $b) - echo "a is bigger than b"; -?> -]]> - </programlisting> - </informalexample> - </para> - <para> - Often you'd want to have more than one statement to be executed - conditionally. Of course, there's no need to wrap each statement - with an <literal>if</literal> clause. Instead, you can group - several statements into a statement group. For example, this code - would display <computeroutput>a is bigger than b</computeroutput> - if <varname>$a</varname> is bigger than - <varname>$b</varname>, and would then assign the value of - <varname>$a</varname> into <varname>$b</varname>: - <informalexample> - <programlisting role="php"> -<![CDATA[ -<?php -if ($a > $b) { - echo "a is bigger than b"; - $b = $a; -} -?> -]]> - </programlisting> - </informalexample> - </para> - <simpara> - <literal>If</literal> statements can be nested infinitely within other - <literal>if</literal> statements, which provides you with complete - flexibility for conditional execution of the various parts of your - program. - </simpara> - </sect1> - - <sect1 xml:id="control-structures.else"> - <title><literal>else</literal></title> - <para> - Often you'd want to execute a statement if a certain condition is - met, and a different statement if the condition is not met. This - is what <literal>else</literal> is for. <literal>else</literal> - extends an <literal>if</literal> statement to execute a statement - in case the expression in the <literal>if</literal> statement - evaluates to &false;. For example, the following - code would display <computeroutput>a is bigger than - b</computeroutput> if <varname>$a</varname> is bigger than - <varname>$b</varname>, and <computeroutput>a is NOT bigger - than b</computeroutput> otherwise: - <informalexample> - <programlisting role="php"> -<![CDATA[ -<?php -if ($a > $b) { - echo "a is bigger than b"; -} else { - echo "a is NOT bigger than b"; -} -?> -]]> - </programlisting> - </informalexample> - - The <literal>else</literal> statement is only executed if the - <literal>if</literal> expression evaluated to - &false;, and if there were any - <literal>elseif</literal> expressions - only if they evaluated to - &false; as well (see <link - linkend="control-structures.elseif">elseif</link>). - - </para> - </sect1> - - <sect1 xml:id="control-structures.elseif"> - <title><literal>elseif</literal>/<literal>else if</literal></title> - <para> - <literal>elseif</literal>, as its name suggests, is a combination - of <literal>if</literal> and <literal>else</literal>. Like - <literal>else</literal>, it extends an <literal>if</literal> - statement to execute a different statement in case the original - <literal>if</literal> expression evaluates to - &false;. However, unlike - <literal>else</literal>, it will execute that alternative - expression only if the <literal>elseif</literal> conditional - expression evaluates to &true;. For example, the - following code would display <computeroutput>a is bigger than - b</computeroutput>, <computeroutput>a equal to b</computeroutput> - or <computeroutput>a is smaller than b</computeroutput>: - <informalexample> - <programlisting role="php"> -<![CDATA[ -<?php -if ($a > $b) { - echo "a is bigger than b"; -} elseif ($a == $b) { - echo "a is equal to b"; -} else { - echo "a is smaller than b"; -} -?> -]]> - </programlisting> - </informalexample> - </para> - <simpara> - There may be several <literal>elseif</literal>s within the same - <literal>if</literal> statement. The first - <literal>elseif</literal> expression (if any) that evaluates to - &true; would be executed. In PHP, you can also - write 'else if' (in two words) and the behavior would be identical - to the one of 'elseif' (in a single word). The syntactic meaning - is slightly different (if you're familiar with C, this is the same - behavior) but the bottom line is that both would result in exactly - the same behavior. - </simpara> - <simpara> - The <literal>elseif</literal> statement is only executed if the - preceding <literal>if</literal> expression and any preceding - <literal>elseif</literal> expressions evaluated to - &false;, and the current - <literal>elseif</literal> expression evaluated to - &true;. - </simpara> - <note> - <simpara> - Note that <literal>elseif</literal> and <literal>else if</literal> - will only be considered exactly the same when using curly brackets - as in the above example. When using a colon to define your - <literal>if</literal>/<literal>elseif</literal> conditions, you must - not separate <literal>else if</literal> into two words, or PHP will - fail with a parse error. - </simpara> - </note> - <para> - <informalexample> - <programlisting role="php"> -<![CDATA[ -<?php - -/* Incorrect Method: */ -if($a > $b): - echo $a." is greater than ".$b; -else if($a == $b): // Will not compile. - echo "The above line causes a parse error."; -endif; - - -/* Correct Method: */ -if($a > $b): - echo $a." is greater than ".$b; -elseif($a == $b): // Note the combination of the words. - echo $a." equals ".$b; -else: - echo $a." is neither greater than or equal to ".$b; -endif; - -?> -]]> - </programlisting> - </informalexample> - </para> - </sect1> - - <sect1 xml:id="control-structures.alternative-syntax"> - <title>Alternative syntax for control structures</title> - <para> - PHP offers an alternative syntax for some of its control - structures; namely, <literal>if</literal>, - <literal>while</literal>, <literal>for</literal>, - <literal>foreach</literal>, and <literal>switch</literal>. - In each case, the basic form of the alternate syntax is to change - the opening brace to a colon (:) and the closing brace to - <literal>endif;</literal>, <literal>endwhile;</literal>, - <literal>endfor;</literal>, <literal>endforeach;</literal>, or - <literal>endswitch;</literal>, respectively. - <informalexample> - <programlisting role="php"> -<![CDATA[ -<?php if ($a == 5): ?> -A is equal to 5 -<?php endif; ?> -]]> - </programlisting> - </informalexample> - </para> - <simpara> - In the above example, the HTML block "A is equal to 5" is nested within an - <literal>if</literal> statement written in the alternative syntax. The - HTML block would be displayed only if <varname>$a</varname> is equal to 5. - </simpara> - <para> - The alternative syntax applies to <literal>else</literal> and - <literal>elseif</literal> as well. The following is an - <literal>if</literal> structure with <literal>elseif</literal> and - <literal>else</literal> in the alternative format: - <informalexample> - <programlisting role="php"> -<![CDATA[ -<?php -if ($a == 5): - echo "a equals 5"; - echo "..."; -elseif ($a == 6): - echo "a equals 6"; - echo "!!!"; -else: - echo "a is neither 5 nor 6"; -endif; -?> -]]> - </programlisting> - </informalexample> - </para> - <para> - See also <link linkend="control-structures.while">while</link>, - <link linkend="control-structures.for">for</link>, and <link - linkend="control-structures.if">if</link> for further examples. - </para> - </sect1> - - <sect1 xml:id="control-structures.while"> - <title><literal>while</literal></title> - <para> - <literal>while</literal> loops are the simplest type of loop in - PHP. They behave just like their C counterparts. The basic form - of a <literal>while</literal> statement is: - <informalexample> - <programlisting> -<![CDATA[ -while (expr) - statement -]]> - </programlisting> - </informalexample> - </para> - <simpara> - The meaning of a <literal>while</literal> statement is simple. It - tells PHP to execute the nested statement(s) repeatedly, as long - as the <literal>while</literal> expression evaluates to - &true;. The value of the expression is checked - each time at the beginning of the loop, so even if this value - changes during the execution of the nested statement(s), execution - will not stop until the end of the iteration (each time PHP runs - the statements in the loop is one iteration). Sometimes, if the - <literal>while</literal> expression evaluates to - &false; from the very beginning, the nested - statement(s) won't even be run once. - </simpara> - <para> - Like with the <literal>if</literal> statement, you can group - multiple statements within the same <literal>while</literal> loop - by surrounding a group of statements with curly braces, or by - using the alternate syntax: - <informalexample> - <programlisting> -<![CDATA[ -while (expr): - statement - ... -endwhile; -]]> - </programlisting> - </informalexample> - </para> - <para> - The following examples are identical, and both print the numbers - 1 through 10: - <informalexample> - <programlisting role="php"> -<![CDATA[ -<?php -/* example 1 */ - -$i = 1; -while ($i <= 10) { - echo $i++; /* the printed value would be - $i before the increment - (post-increment) */ -} - -/* example 2 */ - -$i = 1; -while ($i <= 10): - echo $i; - $i++; -endwhile; -?> -]]> - </programlisting> - </informalexample> - </para> - </sect1> - - <sect1 xml:id="control-structures.do.while"> - <title><literal>do-while</literal></title> - <simpara> - <literal>do-while</literal> loops are very similar to - <literal>while</literal> loops, except the truth expression is - checked at the end of each iteration instead of in the beginning. - The main difference from regular <literal>while</literal> loops is - that the first iteration of a <literal>do-while</literal> loop is - guaranteed to run (the truth expression is only checked at the end - of the iteration), whereas it may not necessarily run with a - regular <literal>while</literal> loop (the truth expression is - checked at the beginning of each iteration, if it evaluates to - &false; right from the beginning, the loop - execution would end immediately). - </simpara> - <para> - There is just one syntax for <literal>do-while</literal> loops: - - <informalexample> - <programlisting role="php"> -<![CDATA[ -<?php -$i = 0; -do { - echo $i; -} while ($i > 0); -?> -]]> - </programlisting> - </informalexample> - </para> - <simpara> - The above loop would run one time exactly, since after the first - iteration, when truth expression is checked, it evaluates to - &false; ($i is not bigger than 0) and the loop - execution ends. - </simpara> - <para> - Advanced C users may be familiar with a different usage of the - <literal>do-while</literal> loop, to allow stopping execution in - the middle of code blocks, by encapsulating them with - <literal>do-while</literal> (0), and using the <link - linkend="control-structures.break"><literal>break</literal></link> - statement. The following code fragment demonstrates this: - <informalexample> - <programlisting role="php"> -<![CDATA[ -<?php -do { - if ($i < 5) { - echo "i is not big enough"; - break; - } - $i *= $factor; - if ($i < $minimum_limit) { - break; - } - echo "i is ok"; - - /* process i */ - -} while (0); -?> -]]> - </programlisting> - </informalexample> - </para> - <simpara> - Don't worry if you don't understand this right away or at all. - You can code scripts and even powerful scripts without using this - 'feature'. - </simpara> - </sect1> - - <sect1 xml:id="control-structures.for"> - <title><literal>for</literal></title> - <para> - <literal>for</literal> loops are the most complex loops in PHP. - They behave like their C counterparts. The syntax of a - <literal>for</literal> loop is: - <informalexample> - <programlisting> -<![CDATA[ -for (expr1; expr2; expr3) - statement -]]> - </programlisting> - </informalexample> - </para> - <simpara> - The first expression (<varname>expr1</varname>) is - evaluated (executed) once unconditionally at the beginning of the - loop. - </simpara> - <simpara> - In the beginning of each iteration, - <varname>expr2</varname> is evaluated. If it evaluates to - &true;, the loop continues and the nested - statement(s) are executed. If it evaluates to - &false;, the execution of the loop ends. - </simpara> - <simpara> - At the end of each iteration, <varname>expr3</varname> is - evaluated (executed). - </simpara> - <simpara> - Each of the expressions can be empty or contain multiple - expressions separated by commas. In <varname>expr2</varname>, all - expressions separated by a comma are evaluated but the result is taken - from the last part. - <varname>expr2</varname> being empty means the loop should - be run indefinitely (PHP implicitly considers it as - &true;, like C). This may not be as useless as - you might think, since often you'd want to end the loop using a - conditional <link - linkend="control-structures.break"><literal>break</literal></link> - statement instead of using the <literal>for</literal> truth - expression. - </simpara> - <para> - Consider the following examples. All of them display the numbers - 1 through 10: - <informalexample> - <programlisting role="php"> -<![CDATA[ -<?php -/* example 1 */ - -for ($i = 1; $i <= 10; $i++) { - echo $i; -} - -/* example 2 */ - -for ($i = 1; ; $i++) { - if ($i > 10) { - break; - } - echo $i; -} - -/* example 3 */ - -$i = 1; -for (; ; ) { - if ($i > 10) { - break; - } - echo $i; - $i++; -} - -/* example 4 */ - -for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++); -?> -]]> - </programlisting> - </informalexample> - </para> - <simpara> - Of course, the first example appears to be the nicest one (or - perhaps the fourth), but you may find that being able to use empty - expressions in <literal>for</literal> loops comes in handy in many - occasions. - </simpara> - <para> - PHP also supports the alternate "colon syntax" for - <literal>for</literal> loops. - <informalexample> - <programlisting> -<![CDATA[ -for (expr1; expr2; expr3): - statement - ... -endfor; -]]> - </programlisting> - </informalexample> - </para> - <simpara> - Its a common thing to many users to iterate though arrays like in the - example below. - </simpara> - <para> - <informalexample> - <programlisting role="php"> -<![CDATA[ -<?php -/* - * This is an array with some data we want to modify - * when running through the for loop. - */ -$people = Array( - Array('name' => 'Kalle', 'salt' => 856412), - Array('name' => 'Pierre', 'salt' => 215863) - ); - -for($i = 0; $i < sizeof($people); ++$i) -{ - $people[$i]['salt'] = rand(000000, 999999); -} -?> -]]> - </programlisting> - </informalexample> - </para> - <simpara> - The problem lies in the second for expression. This code can be slow - because it has to calculate the size of the array on each iteration. - Since the size never change, it can be optimized easily using an - intermediate variable to store the size and use in the loop instead - of sizeof. The example below illustrates this: - </simpara> - <para> - <informalexample> - <programlisting role="php"> -<![CDATA[ -<?php -$people = Array( - Array('name' => 'Kalle', 'salt' => 856412), - Array('name' => 'Pierre', 'salt' => 215863) - ); - -for($i = 0, $size = sizeof($people); $i < $size; ++$i) -{ - $people[$i]['salt'] = rand(000000, 999999); -} -?> -]]> - </programlisting> - </informalexample> - </para> - </sect1> - - <sect1 xml:id="control-structures.foreach"> - <title><literal>foreach</literal></title> - <para> - PHP 4 introduced a <literal>foreach</literal> construct, much - like Perl and some other languages. This simply gives an easy way to - iterate over arrays. <literal>foreach</literal> works only on arrays, and - will issue an error when you try to use it on a variable with a different - data type or an uninitialized variable. There are two syntaxes; the - second is a minor but useful extension of the first: - <informalexample> - <programlisting> -<![CDATA[ -foreach (array_expression as $value) - statement -foreach (array_expression as $key => $value) - statement -]]> - </programlisting> - </informalexample> - </para> - <simpara> - The first form loops over the array given by - <literal>array_expression</literal>. On each loop, the value of - the current element is assigned to <literal>$value</literal> and - the internal array pointer is advanced by one (so on the next - loop, you'll be looking at the next element). - </simpara> - <simpara> - The second form does the same thing, except that the current - element's key will be assigned to the variable - <literal>$key</literal> on each loop. - </simpara> - <simpara> - As of PHP 5, it is possible to - <link linkend="language.oop5.iterations">iterate objects</link> too. - </simpara> - <para> - <note> - <para> - When <literal>foreach</literal> first starts executing, the - internal array pointer is automatically reset to the first element - of the array. This means that you do not need to call - <function>reset</function> before a <literal>foreach</literal> - loop. - </para> - </note> - </para> - <para> - <note> - <para> - Unless the array is <link linkend="language.references">referenced</link>, - <literal>foreach</literal> operates on a copy of - the specified array and not the array itself. <literal>foreach</literal> - has some side effects on the array pointer. Don't rely on the array - pointer during or after the foreach without resetting it. - </para> - </note> - </para> - <para> - As of PHP 5, you can easily modify array's elements by preceding - <literal>$value</literal> with &amp;. This will assign - <link linkend="language.references">reference</link> instead of copying - the value. - <informalexample> - <programlisting role="php"> -<![CDATA[ -<?php -$arr = array(1, 2, 3, 4); -foreach ($arr as &$value) { - $value = $value * 2; -} -// $arr is now array(2, 4, 6, 8) -unset($value); // break the reference with the last element -?> -]]> - </programlisting> - </informalexample> - This is possible only if iterated array can be referenced (i.e. is - variable). - </para> - <warning> - <para> - Reference of a <literal>$value</literal> and the last array element - remain even after the <literal>foreach</literal> loop. It is recommended - to destroy it by <function>unset</function>. - </para> - </warning> - <para> - <note> - <para> - <literal>foreach</literal> does not support the ability to - suppress error messages using '@'. - </para> - </note> - </para> - <para> - You may have noticed that the following are functionally - identical: - <informalexample> - <programlisting role="php"> -<![CDATA[ -<?php -$arr = array("one", "two", "three"); -reset($arr); -while (list(, $value) = each($arr)) { - echo "Value: $value<br />\n"; -} - -foreach ($arr as $value) { - echo "Value: $value<br />\n"; -} -?> -]]> - </programlisting> - </informalexample> - The following are also functionally identical: - <informalexample> - <programlisting role="php"> -<![CDATA[ -<?php -$arr = array("one", "two", "three"); -reset($arr); -while (list($key, $value) = each($arr)) { - echo "Key: $key; Value: $value<br />\n"; -} - -foreach ($arr as $key => $value) { - echo "Key: $key; Value: $value<br />\n"; -} -?> -]]> - </programlisting> - </informalexample> - </para> - <para> - Some more examples to demonstrate usages: - <informalexample> - <programlisting role="php"> -<![CDATA[ -<?php -/* foreach example 1: value only */ - -$a = array(1, 2, 3, 17); - -foreach ($a as $v) { - echo "Current value of \$a: $v.\n"; -} - -/* foreach example 2: value (with its manual access notation printed for illustration) */ - -$a = array(1, 2, 3, 17); - -$i = 0; /* for illustrative purposes only */ - -foreach ($a as $v) { - echo "\$a[$i] => $v.\n"; - $i++; -} - -/* foreach example 3: key and value */ - -$a = array( - "one" => 1, - "two" => 2, - "three" => 3, - "seventeen" => 17 -); - -foreach ($a as $k => $v) { - echo "\$a[$k] => $v.\n"; -} - -/* foreach example 4: multi-dimensional arrays */ -$a = array(); -$a[0][0] = "a"; -$a[0][1] = "b"; -$a[1][0] = "y"; -$a[1][1] = "z"; - -foreach ($a as $v1) { - foreach ($v1 as $v2) { - echo "$v2\n"; - } -} - -/* foreach example 5: dynamic arrays */ - -foreach (array(1, 2, 3, 4, 5) as $v) { - echo "$v\n"; -} -?> -]]> - </programlisting> - </informalexample> - </para> - </sect1> - - <sect1 xml:id="control-structures.break"> - <title><literal>break</literal></title> - <simpara> - <literal>break</literal> ends execution of the current - <literal>for</literal>, <literal>foreach</literal>, - <literal>while</literal>, <literal>do-while</literal> or - <literal>switch</literal> structure. - </simpara> - <simpara> - <literal>break</literal> accepts an optional numeric argument - which tells it how many nested enclosing structures are to be - broken out of. - </simpara> - <para> - <informalexample> - <programlisting role="php"> -<![CDATA[ -<?php -$arr = array('one', 'two', 'three', 'four', 'stop', 'five'); -while (list(, $val) = each($arr)) { - if ($val == 'stop') { - break; /* You could also write 'break 1;' here. */ - } - echo "$val<br />\n"; -} - -/* Using the optional argument. */ - -$i = 0; -while (++$i) { - switch ($i) { - case 5: - echo "At 5<br />\n"; - break 1; /* Exit only the switch. */ - case 10: - echo "At 10; quitting<br />\n"; - break 2; /* Exit the switch and the while. */ - default: - break; - } -} -?> -]]> - </programlisting> - </informalexample> - </para> - </sect1> - - <sect1 xml:id="control-structures.continue"> - <title><literal>continue</literal></title> - <simpara> - <literal>continue</literal> is used within looping structures to - skip the rest of the current loop iteration and continue execution - at the condition evaluation and then the beginning of the next iteration. - </simpara> - <note> - <simpara> - Note that in PHP the - <link linkend="control-structures.switch">switch</link> statement is - considered a looping structure for the purposes of - <literal>continue</literal>. - </simpara> - </note> - <simpara> - <literal>continue</literal> accepts an optional numeric argument - which tells it how many levels of enclosing loops it should skip - to the end of. - </simpara> - <para> - <informalexample> - <programlisting role="php"> -<![CDATA[ -<?php -while (list($key, $value) = each($arr)) { - if (!($key % 2)) { // skip odd members - continue; - } - do_something_odd($value); -} - -$i = 0; -while ($i++ < 5) { - echo "Outer<br />\n"; - while (1) { - echo "&nbsp;&nbsp;Middle<br />\n"; - while (1) { - echo "&nbsp;&nbsp;Inner<br />\n"; - continue 3; - } - echo "This never gets output.<br />\n"; - } - echo "Neither does this.<br />\n"; -} -?> -]]> - </programlisting> - </informalexample> - </para> - <para> - Omitting the semicolon after <literal>continue</literal> can lead to - confusion. Here's an example of what you shouldn't do. - </para> - <para> - <informalexample> - <programlisting role="php"> -<![CDATA[ -<?php - for ($i = 0; $i < 5; ++$i) { - if ($i == 2) - continue - print "$i\n"; - } -?> -]]> - </programlisting> - <para> - One can expect the result to be : - </para> - <screen> -<![CDATA[ -0 -1 -3 -4 -]]> - </screen> - <para> - but this script will output : - </para> - <screen> -<![CDATA[ -2 -]]> - </screen> - <para> - because the return value of the <function>print</function> - call is <literal>int(1)</literal>, and it will look like the - optional numeric argument mentioned above. - </para> - </informalexample> - </para> - </sect1> - - <sect1 xml:id="control-structures.switch"> - <title><literal>switch</literal></title> - <simpara> - The <literal>switch</literal> statement is similar to a series of - IF statements on the same expression. In many occasions, you may - want to compare the same variable (or expression) with many - different values, and execute a different piece of code depending - on which value it equals to. This is exactly what the - <literal>switch</literal> statement is for. - </simpara> - <note> - <simpara> - Note that unlike some other languages, the - <link linkend="control-structures.continue">continue</link> statement - applies to switch and acts similar to <literal>break</literal>. If you - have a switch inside a loop and wish to continue to the next iteration of - the outer loop, use <literal>continue 2</literal>. - </simpara> - </note> - <note> - <para> - Note that switch/case does - <link linkend="types.comparisions-loose">loose comparision</link>. - </para> - </note> - <para> - The following two examples are two different ways to write the - same thing, one using a series of <literal>if</literal> and - <literal>elseif</literal> statements, and the other using the - <literal>switch</literal> statement: - <example> - <title><literal>switch</literal> structure</title> - <programlisting role="php"> -<![CDATA[ -<?php -if ($i == 0) { - echo "i equals 0"; -} elseif ($i == 1) { - echo "i equals 1"; -} elseif ($i == 2) { - echo "i equals 2"; -} - -switch ($i) { -case 0: - echo "i equals 0"; - break; -case 1: - echo "i equals 1"; - break; -case 2: - echo "i equals 2"; - break; -} -?> -]]> - </programlisting> - </example> - <example> - <title><literal>switch</literal> structure allows usage of strings</title> - <programlisting role="php"> -<![CDATA[ -<?php -switch ($i) { -case "apple": - echo "i is apple"; - break; -case "bar": - echo "i is bar"; - break; -case "cake": - echo "i is cake"; - break; -} -?> -]]> - </programlisting> - </example> - </para> - <para> - It is important to understand how the <literal>switch</literal> - statement is executed in order to avoid mistakes. The - <literal>switch</literal> statement executes line by line - (actually, statement by statement). In the beginning, no code is - executed. Only when a <literal>case</literal> statement is found - with a value that matches the value of the - <literal>switch</literal> expression does PHP begin to execute the - statements. PHP continues to execute the statements until the end - of the <literal>switch</literal> block, or the first time it sees - a <literal>break</literal> statement. If you don't write a - <literal>break</literal> statement at the end of a case's - statement list, PHP will go on executing the statements of the - following case. For example: - <informalexample> - <programlisting role="php"> -<![CDATA[ -<?php -switch ($i) { -case 0: - echo "i equals 0"; -case 1: - echo "i equals 1"; -case 2: - echo "i equals 2"; -} -?> -]]> - </programlisting> - </informalexample> - </para> - <simpara> - Here, if <varname>$i</varname> is equal to 0, PHP would execute all of the echo - statements! If <varname>$i</varname> is equal to 1, PHP would execute the last two - echo statements. You would get the expected behavior ('i equals 2' - would be displayed) only if <varname>$i</varname> is equal to 2. Thus, - it is important not to forget <literal>break</literal> statements - (even though you may want to avoid supplying them on purpose under - certain circumstances). - </simpara> - <simpara> - In a <literal>switch</literal> statement, the condition is - evaluated only once and the result is compared to each - <literal>case</literal> statement. In an <literal>elseif</literal> - statement, the condition is evaluated again. If your condition is - more complicated than a simple compare and/or is in a tight loop, - a <literal>switch</literal> may be faster. - </simpara> - <para> - The statement list for a case can also be empty, which simply - passes control into the statement list for the next case. - <informalexample> - <programlisting role="php"> -<![CDATA[ -<?php -switch ($i) { -case 0: -case 1: -case 2: - echo "i is less than 3 but not negative"; - break; -case 3: - echo "i is 3"; -} -?> -]]> - </programlisting> - </informalexample> - </para> - <para> - A special case is the <literal>default</literal> case. This case matches - anything that wasn't matched by the other cases. For example: - <informalexample> - <programlisting role="php"> -<![CDATA[ -<?php -switch ($i) { -case 0: - echo "i equals 0"; - break; -case 1: - echo "i equals 1"; - break; -case 2: - echo "i equals 2"; - break; -default: - echo "i is not equal to 0, 1 or 2"; -} -?> -]]> - </programlisting> - </informalexample> - </para> - <para> - The <literal>case</literal> expression may be any expression that - evaluates to a simple type, that is, integer or floating-point - numbers and strings. Arrays or objects cannot be used here unless - they are dereferenced to a simple type. - </para> - <para> - The alternative syntax for control structures is supported with - switches. For more information, see <link - linkend="control-structures.alternative-syntax">Alternative syntax - for control structures</link>. - <informalexample> - <programlisting role="php"> -<![CDATA[ -<?php -switch ($i): -case 0: - echo "i equals 0"; - break; -case 1: - echo "i equals 1"; - break; -case 2: - echo "i equals 2"; - break; -default: - echo "i is not equal to 0, 1 or 2"; -endswitch; -?> -]]> - </programlisting> - </informalexample> - </para> - <para> - Its possible to use a semicolon instead of a colon after a case like: - <informalexample> - <programlisting role="php"> -<![CDATA[ -<?php -switch($beer) -{ - case 'tuborg'; - case 'carlsberg'; - case 'heineken'; - echo 'Good choice'; - break; - default; - echo 'Please make a new selection...'; - break; -} -?> -]]> - </programlisting> - </informalexample> - </para> - </sect1> - - <sect1 xml:id="control-structures.declare"> - <title><literal>declare</literal></title> - <para> - The <literal>declare</literal> construct is used to - set execution directives for a block of code. - The syntax of <literal>declare</literal> is similar to - the syntax of other flow control constructs: - <informalexample> - <programlisting> -<![CDATA[ -declare (directive) - statement -]]> - </programlisting> - </informalexample> - </para> - <para> - The <literal>directive</literal> section allows the - behavior of the <literal>declare</literal> block to - be set. - Currently only two directives are recognized: the - <literal>ticks</literal> directive (See below for more - information on the - <link linkend="control-structures.declare.ticks">ticks</link> - directive) and the <literal>encoding</literal> directive (See below for more - information on the - <link linkend="control-structures.declare.encoding">encoding</link> - directive). - </para> - <note> - <simpara> - The encoding directive was added in PHP 5.3.0 - </simpara> - </note> - <para> - The <literal>statement</literal> part of the - <literal>declare</literal> block will be executed - how - it is executed and what side effects occur during execution - may depend on the directive set in the - <literal>directive</literal> block. - </para> - <para> - The <literal>declare</literal> construct can also be used in the global - scope, affecting all code following it (however if the file with - <literal>declare</literal> was included then it does not affect the parent - file). - <informalexample> - <programlisting role="php"> -<![CDATA[ -<?php -// these are the same: - -// you can use this: -declare(ticks=1) { - // entire script here -} - -// or you can use this: -declare(ticks=1); -// entire script here -?> -]]> - </programlisting> - </informalexample> - </para> - <sect2 xml:id="control-structures.declare.ticks"> - <title>Ticks</title> - <caution> - <simpara> - As of PHP 5.3.0 ticks are deprecated and will be removed - in PHP 6.0.0. - </simpara> - </caution> - <para>A tick is an event that occurs for every - <varname>N</varname> low-level statements executed - by the parser within the <literal>declare</literal> block. - The value for <varname>N</varname> is specified - using <code>ticks=<varname>N</varname></code> - within the <literal>declare</literal> blocks's - <literal>directive</literal> section. - </para> - <para> - The event(s) that occur on each tick are specified using the - <function>register_tick_function</function>. See the example - below for more details. Note that more than one event can occur - for each tick. - </para> - <para> - <example> - <title>Profile a section of PHP code</title> - <programlisting role="php"> -<![CDATA[ -<?php -// A function that records the time when it is called -function profile($dump = FALSE) -{ - static $profile; - - // Return the times stored in profile, then erase it - if ($dump) { - $temp = $profile; - unset($profile); - return $temp; - } - - $profile[] = microtime(); -} - -// Set up a tick handler -register_tick_function("profile"); - -// Initialize the function before the declare block -profile(); - -// Run a block of code, throw a tick every 2nd statement -declare(ticks=2) { - for ($x = 1; $x < 50; ++$x) { - echo similar_text(md5($x), md5($x*$x)), "<br />;"; - } -} - -// Display the data stored in the profiler -print_r(profile(TRUE)); -?> -]]> - </programlisting> - </example> - The example profiles the PHP code within the 'declare' - block, recording the time at which every second low-level - statement in the block was executed. This information can - then be used to find the slow areas within particular - segments of code. This process can be performed using other - methods: using ticks is more convenient and easier to - implement. - </para> - <simpara> - Ticks are well suited for debugging, implementing simple - multitasking, background I/O and many other tasks. - </simpara> - <simpara> - See also <function>register_tick_function</function> and - <function>unregister_tick_function</function>. - </simpara> - </sect2> - <sect2 xml:id="control-structures.declare.encoding"> - <title>Encoding</title> - <para> - A script's encoding can be specified per-script using the encoding directive. - <example> - <title>Declaring an encoding for the script.</title> - <programlisting role="php"> -<![CDATA[ -<?php -declare(encoding='ISO-8859-1'); -// code here -?> -]]> - </programlisting> - </example> - </para> - - <caution> - <simpara> - When combined with namespaces, the only legal syntax for declare - is <literal>declare(encoding='...');</literal> where <literal>...</literal> - is the encoding value. <literal>declare(encoding='...') {}</literal> - will result in a parse error when combined with namespaces. - </simpara> - </caution> - <para> - The encoding declare value is ignored in PHP 5.3 unless php is compiled with - <literal>--enable-zend-multibyte</literal>. In PHP 6.0, the <literal>encoding</literal> - directive will be used to inform the scanner what encoding the file is created in. Legal - values are encoding names such as <literal>UTF-8</literal>. - </para> - </sect2> - </sect1> - - <sect1 xml:id="function.return"> - <title>return</title> - <simpara> - If called from within a function, the <function>return</function> - statement immediately ends execution of the current function, and - returns its argument as the value of the function - call. <function>return</function> will also end the execution of - an <function>eval</function> statement or script file. - </simpara> - <simpara> - If called from the global scope, then execution of the current - script file is ended. If the current script file was - <function>include</function>ed or <function>require</function>ed, - then control is passed back to the calling file. Furthermore, if - the current script file was <function>include</function>ed, then - the value given to <function>return</function> will be returned as - the value of the <function>include</function> call. If - <function>return</function> is called from within the main script - file, then script execution ends. If the current script file was - named by the <link - linkend="ini.auto-prepend-file">auto_prepend_file</link> or <link - linkend="ini.auto-append-file">auto_append_file</link> - configuration options in &php.ini;, - then that script file's execution is ended. - </simpara> - <simpara>For more information, see <link - linkend="functions.returning-values">Returning values</link>. - </simpara> - <para> - <note> - <simpara> - Note that since <function>return</function> is a language - construct and not a function, the parentheses surrounding its - arguments are not required. It is common to leave them out, and you - actually should do so as PHP has less work to do in this case. - </simpara> - </note> - <note> - <simpara> - You should <emphasis>never</emphasis> use parentheses around your return - variable when returning by reference, as this will not work. You can - only return variables by reference, not the result of a statement. If - you use <literal>return ($a);</literal> then you're not returning a - variable, but the result of the expression <literal>($a)</literal> - (which is, of course, the value of <varname>$a</varname>). - </simpara> - </note> - </para> - </sect1> - - - <sect1 xml:id="function.require"> - <title><function>require</function></title> - - <simpara> - The <function>require</function> statement includes and evaluates - the specific file. - </simpara> - <simpara> - <function>require</function> includes and evaluates a specific file. - Detailed information on how this inclusion works is described in the - documentation for <function>include</function>. - </simpara> - <simpara> - <function>require</function> and <function>include</function> - are identical in every way except how they handle failure. They both - produce a <link linkend="errorfunc.constants.errorlevels.e-warning">Warning</link>, but - <function>require</function> results in a <link linkend="errorfunc.constants.errorlevels.e-error"> - Fatal Error</link>. In other words, don't hesitate to use - <function>require</function> if you want a missing file to halt processing - of the page. <function>include</function> does not behave this way, the - script will continue regardless. Be sure to have an appropriate - <link linkend="ini.include-path">include_path</link> setting as well. - </simpara> - <para> - <example> - <title>Basic <function>require</function> examples</title> - <programlisting role="php"> -<![CDATA[ -<?php - -require 'prepend.php'; - -require $somefile; - -require ('somefile.txt'); - -?> -]]> - </programlisting> - </example> - </para> - <simpara> - See the <function>include</function> documentation for more examples. - </simpara> - <para> - <note> - <simpara> - Prior to PHP 4.0.2, the following applies: <function>require</function> - will always attempt to read the target file, even if the line it's on - never executes. The conditional statement won't affect - <function>require</function>. However, if the line on which the - <function>require</function> occurs is not executed, neither will any of - the code in the target file be executed. Similarly, looping structures - do not affect the behaviour of <function>require</function>. Although - the code contained in the target file is still subject to the loop, the - <function>require</function> itself happens only once. - </simpara> - </note> - </para> - - &note.language-construct; - - &warn.no-win32-fopen-wrapper; - - <simpara> - See also <function>include</function>, <function>require_once</function>, - <function>include_once</function>, <function>get_included_files</function>, - <function>eval</function>, <function>file</function>, <function>readfile</function>, - <function>virtual</function> and <link linkend="ini.include-path">include_path</link>. - </simpara> - </sect1> - - <sect1 xml:id="function.include"> - <title><function>include</function></title> - <simpara> - The <function>include</function> statement includes and evaluates - the specified file. - </simpara> - <simpara> - The documentation below also applies to <function>require</function>. - The two constructs are identical in every way except how they handle - failure. They both produce a - <link linkend="errorfunc.constants.errorlevels.e-warning">Warning</link>, but <function>require</function> - results in a <link linkend="errorfunc.constants.errorlevels.e-error">Fatal Error</link>. - In other words, use <function>require</function> if you want - a missing file to halt processing of the page. <function>include</function> does - not behave this way, the script will continue regardless. Be sure to have an - appropriate <link linkend="ini.include-path">include_path</link> setting as well. - Be warned that parse error in included file doesn't cause processing halting - in PHP versions prior to PHP 4.3.5. Since this version, it does. - </simpara> - <simpara> - Files for including are first looked for in each include_path entry - relative to the current working directory, and then in the directory of - current script. - E.g. if your include_path - is <literal>libraries</literal>, current working directory is <filename class="directory">/www/</filename>, - you included <filename>include/a.php</filename> and there is <literal>include "b.php"</literal> - in that file, <filename>b.php</filename> is first looked in <filename class="directory">/www/libraries/</filename> - and then in <filename class="directory">/www/include/</filename>. - If filename begins with <literal>./</literal> or <literal>../</literal>, it - is looked only in the current working directory. - </simpara> - <simpara> - When a file is included, the code it contains inherits the - <link linkend="language.variables.scope">variable scope</link> of the - line on which the include occurs. Any variables available at that line - in the calling file will be available within the called file, from that - point forward. - However, all functions and classes defined in the included file have the - global scope. - </simpara> - <para> - <example> - <title>Basic <function>include</function> example</title> - <programlisting role="php"> -<![CDATA[ -vars.php -<?php - -$color = 'green'; -$fruit = 'apple'; - -?> - -test.php -<?php - -echo "A $color $fruit"; // A - -include 'vars.php'; - -echo "A $color $fruit"; // A green apple - -?> -]]> - </programlisting> - </example> - </para> - <simpara> - If the include occurs inside a function within the calling file, - then all of the code contained in the called file will behave as - though it had been defined inside that function. So, it will follow - the variable scope of that function. - An exception to this rule are <link - linkend="language.constants.predefined">magic constants</link> which are - evaluated by the parser before the include occurs. - </simpara> - <para> - <example> - <title>Including within functions</title> - <programlisting role="php"> -<![CDATA[ -<?php - -function foo() -{ - global $color; - - include 'vars.php'; - - echo "A $color $fruit"; -} - -/* vars.php is in the scope of foo() so * - * $fruit is NOT available outside of this * - * scope. $color is because we declared it * - * as global. */ - -foo(); // A green apple -echo "A $color $fruit"; // A green - -?> -]]> - </programlisting> - </example> - </para> - <simpara> - When a file is included, parsing drops out of PHP mode and - into HTML mode at the beginning of the target file, and resumes - again at the end. For this reason, any code inside the target - file which should be executed as PHP code must be enclosed within - <link linkend="language.basic-syntax.phpmode">valid PHP start - and end tags</link>. - </simpara> - <simpara> - If "<link linkend="ini.allow-url-fopen">URL fopen wrappers</link>" - are enabled in PHP (which they are in the default configuration), - you can specify the file to be included using a URL (via HTTP or - other supported wrapper - see <xref linkend="wrappers"/> for a list - of protocols) instead of a local pathname. If the target server interprets - the target file as PHP code, variables may be passed to the included - file using a URL request string as used with HTTP GET. This is - not strictly speaking the same thing as including the file and having - it inherit the parent file's variable scope; the script is actually - being run on the remote server and the result is then being - included into the local script. - </simpara> - &warn.no-win32-fopen-wrapper; - <para> - <example> - <title><function>include</function> through HTTP</title> - <programlisting role="php"> -<![CDATA[ -<?php - -/* This example assumes that www.example.com is configured to parse .php - * files and not .txt files. Also, 'Works' here means that the variables - * $foo and $bar are available within the included file. */ - -// Won't work; file.txt wasn't handled by www.example.com as PHP -include 'http://www.example.com/file.txt?foo=1&bar=2'; - -// Won't work; looks for a file named 'file.php?foo=1&bar=2' on the -// local filesystem. -include 'file.php?foo=1&bar=2'; - -// Works. -include 'http://www.example.com/file.php?foo=1&bar=2'; - -$foo = 1; -$bar = 2; -include 'file.txt'; // Works. -include 'file.php'; // Works. - -?> -]]> - </programlisting> - </example> - </para> - <warning> - <title>Security warning</title> - <para> - Remote file may be processed at the remote server (depending on the file - extension and the fact if the remote server runs PHP or not) but it still - has to produce a valid PHP script because it will be processed at the - local server. If the file from the remote server should be processed - there and outputted only, <function>readfile</function> is much better - function to use. Otherwise, special care should be taken to secure the - remote script to produce a valid and desired code. - </para> - </warning> - <para> - See also <link linkend="features.remote-files">Remote files</link>, - <function>fopen</function> and <function>file</function> for related - information. - </para> - <simpara> - Handling Returns: It is possible to execute a <function>return</function> - statement inside an included file in order to terminate processing in that - file and return to the script which called it. Also, it's possible to return - values from included files. You can take the value of the include call as - you would a normal function. This is not, however, possible when including - remote files unless the output of the remote file has - <link linkend="language.basic-syntax.phpmode">valid PHP start - and end tags</link> (as with any local file). You can declare the needed - variables within those tags and they will be introduced at whichever point - the file was included. - </simpara> - <para> - Because <function>include</function> is a special language construct, - parentheses are not needed around its argument. Take care when comparing - return value. - <example> - <title>Comparing return value of include</title> - <programlisting role="php"> -<![CDATA[ -<?php -// won't work, evaluated as include(('vars.php') == 'OK'), i.e. include('') -if (include('vars.php') == 'OK') { - echo 'OK'; -} - -// works -if ((include 'vars.php') == 'OK') { - echo 'OK'; -} -?> -]]> - </programlisting> - </example> - </para> - <para> - <example> - <title><function>include</function> and the <function>return</function> statement</title> - <programlisting role="php"> -<![CDATA[ -return.php -<?php - -$var = 'PHP'; - -return $var; - -?> - -noreturn.php -<?php - -$var = 'PHP'; - -?> - -testreturns.php -<?php - -$foo = include 'return.php'; - -echo $foo; // prints 'PHP' - -$bar = include 'noreturn.php'; - -echo $bar; // prints 1 - -?> -]]> - </programlisting> - </example> - </para> - <simpara> - <literal>$bar</literal> is the value <literal>1</literal> because the include - was successful. Notice the difference between the above examples. The first uses - <function>return</function> within the included file while the other does not. - If the file can't be included, &false; is returned and - <literal>E_WARNING</literal> is issued. - </simpara> - <para> - If there are functions defined in the included file, they can be used in the - main file independent if they are before <function>return</function> or after. - If the file is included twice, PHP 5 issues fatal error because functions - were already declared, while PHP 4 doesn't complain about functions - defined after <function>return</function>. - It is recommended to use <function>include_once</function> instead of - checking if the file was already included and conditionally return inside - the included file. - </para> - <simpara> - Another way to "include" a PHP file into a variable is to capture the - output by using the <link linkend="ref.outcontrol">Output Control - Functions</link> with <function>include</function>. For example: - </simpara> - <para> - <example> - <title>Using output buffering to include a PHP file into a string</title> - <programlisting role="php"> -<![CDATA[ -<?php -$string = get_include_contents('somefile.php'); - -function get_include_contents($filename) { - if (is_file($filename)) { - ob_start(); - include $filename; - $contents = ob_get_contents(); - ob_end_clean(); - return $contents; - } - return false; -} - -?> -]]> - </programlisting> - </example> - </para> - <para> - In order to automatically include files within scripts, see also the - <link linkend="ini.auto-prepend-file">auto_prepend_file</link> and - <link linkend="ini.auto-append-file">auto_append_file</link> - configuration options in &php.ini;. - </para> - - &note.language-construct; - - <simpara> - See also <function>require</function>, <function>require_once</function>, - <function>include_once</function>, <function>get_included_files</function>, - <function>readfile</function>, <function>virtual</function>, and - <link linkend="ini.include-path">include_path</link>. - </simpara> +<?xml version="1.0" encoding="utf-8"?> +<!-- $Revision: 1.174 $ --> +<chapter xml:id="language.control-structures" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink"> + <title>Control Structures</title> + + <sect1 xml:id="control-structures.intro"> + <title>Introduction</title> + <simpara> + Any PHP script is built out of a series of statements. A statement + can be an assignment, a function call, a loop, a conditional + statement or even a statement that does nothing (an empty + statement). Statements usually end with a semicolon. In addition, + statements can be grouped into a statement-group by encapsulating a + group of statements with curly braces. A statement-group is a + statement by itself as well. The various statement types are + described in this chapter. + </simpara> </sect1> - <sect1 xml:id="function.require-once"> - <title><function>require_once</function></title> - <para> - The <function>require_once</function> statement includes and evaluates - the specified file during the execution of the script. - This is a behavior similar to the <function>require</function> statement, - with the only difference being that if the code from a file has already - been included, it will not be included again. See the documentation for - <function>require</function> for more information on how this statement - works. - </para> - <para> - <function>require_once</function> should be used in cases where - the same file might be included and evaluated more than once during a - particular execution of a script, and you want to be sure that it is - included exactly once to avoid problems with function redefinitions, - variable value reassignments, etc. - </para> - <para> - For examples on using <function>require_once</function> and - <function>include_once</function>, look at the - <link xlink:href="&url.php.pear;">PEAR</link> code included in the - latest PHP source code distributions. - </para> - <para> - Return values are the same as with <function>include</function>. If the file - was already included, this function returns &true; - </para> - <para> - <note> - <para> - <function>require_once</function> was added in PHP 4.0.1 - </para> - </note> - </para> - <para> - <note> - <para> - Be aware, that the behaviour of <function>require_once</function> - and <function>include_once</function> may not be what you expect - on a non case sensitive operating system (such as Windows). - <example> - <title><function>require_once</function> is case insensitive on Windows</title> - <programlisting role="php"> -<![CDATA[ -<?php -require_once "a.php"; // this will include a.php -require_once "A.php"; // this will include a.php again on Windows! (PHP 4 only) -?> -]]> - </programlisting> - </example> - This behaviour changed in PHP 5 - the path is normalized first so that - <filename>C:\PROGRA~1\A.php</filename> is realized the same as - <filename>C:\Program Files\a.php</filename> and the file is required just once. - </para> - </note> - </para> - &warn.no-win32-fopen-wrapper; - <para> - See also <function>require</function>, - <function>include</function>, <function>include_once</function>, - <function>get_required_files</function>, - <function>get_included_files</function>, <function>readfile</function>, and - <function>virtual</function>. - </para> - </sect1> + &language.control-structures.if; + &language.control-structures.else; + &language.control-structures.elseif; + &language.control-structures.alternative-syntax; + &language.control-structures.while; + &language.control-structures.do-while; + &language.control-structures.for; + &language.control-structures.foreach; + &language.control-structures.break; + &language.control-structures.continue; + &language.control-structures.switch; + &language.control-structures.declare; + &language.control-structures.return; + &language.control-structures.require; + &language.control-structures.include; + &language.control-structures.require-once; + &language.control-structures.include-once; - <sect1 xml:id="function.include-once"> - <title><function>include_once</function></title> - <para> - The <function>include_once</function> statement includes and evaluates - the specified file during the execution of the script. - This is a behavior similar to the <function>include</function> statement, - with the only difference being that if the code from a file has already - been included, it will not be included again. As the name suggests, - it will be included just once. - </para> - <para> - <function>include_once</function> should be used in cases where - the same file might be included and evaluated more than once during a - particular execution of a script, and you want to be sure that it is - included exactly once to avoid problems with function redefinitions, - variable value reassignments, etc. - </para> - <para> - For more examples on using <function>require_once</function> and - <function>include_once</function>, look at the - <link xlink:href="&url.php.pear;">PEAR</link> code included in the latest - PHP source code distributions. - </para> - <para> - Return values are the same as with <function>include</function>. If the file - was already included, this function returns &true; - </para> - <para> - <note> - <para> - <function>include_once</function> was added in PHP 4.0.1 - </para> - </note> - </para> - <para> - <note> - <para> - Be aware, that the behaviour of <function>include_once</function> - and <function>require_once</function> may not be what you expect - on a non case sensitive operating system (such as Windows). - <example> - <title><function>include_once</function> is case insensitive on Windows</title> - <programlisting role="php"> -<![CDATA[ -<?php -include_once "a.php"; // this will include a.php -include_once "A.php"; // this will include a.php again on Windows! (PHP 4 only) -?> -]]> - </programlisting> - </example> - This behaviour changed in PHP 5 - the path is normalized first so that - <filename>C:\PROGRA~1\A.php</filename> is realized the same as - <filename>C:\Program Files\a.php</filename> and the file is included just once. - </para> - </note> - </para> - &warn.no-win32-fopen-wrapper; - <para> - See also <function>include</function>, - <function>require</function>, <function>require_once</function>, - <function>get_required_files</function>, - <function>get_included_files</function>, <function>readfile</function>, - and <function>virtual</function>. - </para> - </sect1> - - </chapter> +</chapter> <!-- Keep this comment at the end of the file Local variables: http://cvs.php.net/viewvc.cgi/phpdoc/en/language/control-structures/alternative-syntax.xml?view=markup&rev=1.1 Index: phpdoc/en/language/control-structures/alternative-syntax.xml +++ phpdoc/en/language/control-structures/alternative-syntax.xml <?xml version="1.0" encoding="utf-8"?> <!-- $Revision: 1.1 $ --> <sect1 xml:id="control-structures.alternative-syntax" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink"> <title>Alternative syntax for control structures</title> <para> PHP offers an alternative syntax for some of its control structures; namely, <literal>if</literal>, <literal>while</literal>, <literal>for</literal>, <literal>foreach</literal>, and <literal>switch</literal>. In each case, the basic form of the alternate syntax is to change the opening brace to a colon (:) and the closing brace to <literal>endif;</literal>, <literal>endwhile;</literal>, <literal>endfor;</literal>, <literal>endforeach;</literal>, or <literal>endswitch;</literal>, respectively. <informalexample> <programlisting role="php"> <![CDATA[ <?php if ($a == 5): ?> A is equal to 5 <?php endif; ?> ]]> </programlisting> </informalexample> </para> <simpara> In the above example, the HTML block "A is equal to 5" is nested within an <literal>if</literal> statement written in the alternative syntax. The HTML block would be displayed only if <varname>$a</varname> is equal to 5. </simpara> <para> The alternative syntax applies to <literal>else</literal> and <literal>elseif</literal> as well. The following is an <literal>if</literal> structure with <literal>elseif</literal> and <literal>else</literal> in the alternative format: <informalexample> <programlisting role="php"> <![CDATA[ <?php if ($a == 5): echo "a equals 5"; echo "..."; elseif ($a == 6): echo "a equals 6"; echo "!!!"; else: echo "a is neither 5 nor 6"; endif; ?> ]]> </programlisting> </informalexample> </para> <para> See also <link linkend="control-structures.while">while</link>, <link linkend="control-structures.for">for</link>, and <link linkend="control-structures.if">if</link> for further examples. </para> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/viewvc.cgi/phpdoc/en/language/control-structures/break.xml?view=markup&rev=1.1 Index: phpdoc/en/language/control-structures/break.xml +++ phpdoc/en/language/control-structures/break.xml <?xml version="1.0" encoding="utf-8"?> <!-- $Revision: 1.1 $ --> <sect1 xml:id="control-structures.break" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink"> <title><literal>break</literal></title> <simpara> <literal>break</literal> ends execution of the current <literal>for</literal>, <literal>foreach</literal>, <literal>while</literal>, <literal>do-while</literal> or <literal>switch</literal> structure. </simpara> <simpara> <literal>break</literal> accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of. </simpara> <para> <informalexample> <programlisting role="php"> <![CDATA[ <?php $arr = array('one', 'two', 'three', 'four', 'stop', 'five'); while (list(, $val) = each($arr)) { if ($val == 'stop') { break; /* You could also write 'break 1;' here. */ } echo "$val<br />\n"; } /* Using the optional argument. */ $i = 0; while (++$i) { switch ($i) { case 5: echo "At 5<br />\n"; break 1; /* Exit only the switch. */ case 10: echo "At 10; quitting<br />\n"; break 2; /* Exit the switch and the while. */ default: break; } } ?> ]]> </programlisting> </informalexample> </para> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/viewvc.cgi/phpdoc/en/language/control-structures/continue.xml?view=markup&rev=1.1 Index: phpdoc/en/language/control-structures/continue.xml +++ phpdoc/en/language/control-structures/continue.xml <?xml version="1.0" encoding="utf-8"?> <!-- $Revision: 1.1 $ --> <sect1 xml:id="control-structures.continue" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink"> <title><literal>continue</literal></title> <simpara> <literal>continue</literal> is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration. </simpara> <note> <simpara> Note that in PHP the <link linkend="control-structures.switch">switch</link> statement is considered a looping structure for the purposes of <literal>continue</literal>. </simpara> </note> <simpara> <literal>continue</literal> accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of. </simpara> <para> <informalexample> <programlisting role="php"> <![CDATA[ <?php while (list($key, $value) = each($arr)) { if (!($key % 2)) { // skip odd members continue; } do_something_odd($value); } $i = 0; while ($i++ < 5) { echo "Outer<br />\n"; while (1) { echo "&nbsp;&nbsp;Middle<br />\n"; while (1) { echo "&nbsp;&nbsp;Inner<br />\n"; continue 3; } echo "This never gets output.<br />\n"; } echo "Neither does this.<br />\n"; } ?> ]]> </programlisting> </informalexample> </para> <para> Omitting the semicolon after <literal>continue</literal> can lead to confusion. Here's an example of what you shouldn't do. </para> <para> <informalexample> <programlisting role="php"> <![CDATA[ <?php for ($i = 0; $i < 5; ++$i) { if ($i == 2) continue print "$i\n"; } ?> ]]> </programlisting> <para> One can expect the result to be : </para> <screen> <![CDATA[ 0 1 3 4 ]]> </screen> <para> but this script will output : </para> <screen> <![CDATA[ 2 ]]> </screen> <para> because the return value of the <function>print</function> call is <literal>int(1)</literal>, and it will look like the optional numeric argument mentioned above. </para> </informalexample> </para> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/viewvc.cgi/phpdoc/en/language/control-structures/declare.xml?view=markup&rev=1.1 Index: phpdoc/en/language/control-structures/declare.xml +++ phpdoc/en/language/control-structures/declare.xml <?xml version="1.0" encoding="utf-8"?> <!-- $Revision: 1.1 $ --> <sect1 xml:id="control-structures.declare" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink"> <title><literal>declare</literal></title> <para> The <literal>declare</literal> construct is used to set execution directives for a block of code. The syntax of <literal>declare</literal> is similar to the syntax of other flow control constructs: <informalexample> <programlisting> <![CDATA[ declare (directive) statement ]]> </programlisting> </informalexample> </para> <para> The <literal>directive</literal> section allows the behavior of the <literal>declare</literal> block to be set. Currently only two directives are recognized: the <literal>ticks</literal> directive (See below for more information on the <link linkend="control-structures.declare.ticks">ticks</link> directive) and the <literal>encoding</literal> directive (See below for more information on the <link linkend="control-structures.declare.encoding">encoding</link> directive). </para> <note> <simpara> The encoding directive was added in PHP 5.3.0 </simpara> </note> <para> The <literal>statement</literal> part of the <literal>declare</literal> block will be executed - how it is executed and what side effects occur during execution may depend on the directive set in the <literal>directive</literal> block. </para> <para> The <literal>declare</literal> construct can also be used in the global scope, affecting all code following it (however if the file with <literal>declare</literal> was included then it does not affect the parent file). <informalexample> <programlisting role="php"> <![CDATA[ <?php // these are the same: // you can use this: declare(ticks=1) { // entire script here } // or you can use this: declare(ticks=1); // entire script here ?> ]]> </programlisting> </informalexample> </para> <sect2 xml:id="control-structures.declare.ticks"> <title>Ticks</title> <caution> <simpara> As of PHP 5.3.0 ticks are deprecated and will be removed in PHP 6.0.0. </simpara> </caution> <para>A tick is an event that occurs for every <varname>N</varname> low-level statements executed by the parser within the <literal>declare</literal> block. The value for <varname>N</varname> is specified using <code>ticks=<varname>N</varname></code> within the <literal>declare</literal> blocks's <literal>directive</literal> section. </para> <para> The event(s) that occur on each tick are specified using the <function>register_tick_function</function>. See the example below for more details. Note that more than one event can occur for each tick. </para> <para> <example> <title>Profile a section of PHP code</title> <programlisting role="php"> <![CDATA[ <?php // A function that records the time when it is called function profile($dump = FALSE) { static $profile; // Return the times stored in profile, then erase it if ($dump) { $temp = $profile; unset($profile); return $temp; } $profile[] = microtime(); } // Set up a tick handler register_tick_function("profile"); // Initialize the function before the declare block profile(); // Run a block of code, throw a tick every 2nd statement declare(ticks=2) { for ($x = 1; $x < 50; ++$x) { echo similar_text(md5($x), md5($x*$x)), "<br />;"; } } // Display the data stored in the profiler print_r(profile(TRUE)); ?> ]]> </programlisting> </example> The example profiles the PHP code within the 'declare' block, recording the time at which every second low-level statement in the block was executed. This information can then be used to find the slow areas within particular segments of code. This process can be performed using other methods: using ticks is more convenient and easier to implement. </para> <simpara> Ticks are well suited for debugging, implementing simple multitasking, background I/O and many other tasks. </simpara> <simpara> See also <function>register_tick_function</function> and <function>unregister_tick_function</function>. </simpara> </sect2> <sect2 xml:id="control-structures.declare.encoding"> <title>Encoding</title> <para> A script's encoding can be specified per-script using the encoding directive. <example> <title>Declaring an encoding for the script.</title> <programlisting role="php"> <![CDATA[ <?php declare(encoding='ISO-8859-1'); // code here ?> ]]> </programlisting> </example> </para> <caution> <simpara> When combined with namespaces, the only legal syntax for declare is <literal>declare(encoding='...');</literal> where <literal>...</literal> is the encoding value. <literal>declare(encoding='...') {}</literal> will result in a parse error when combined with namespaces. </simpara> </caution> <para> The encoding declare value is ignored in PHP 5.3 unless php is compiled with <literal>--enable-zend-multibyte</literal>. In PHP 6.0, the <literal>encoding</literal> directive will be used to inform the scanner what encoding the file is created in. Legal values are encoding names such as <literal>UTF-8</literal>. </para> </sect2> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/viewvc.cgi/phpdoc/en/language/control-structures/do-while.xml?view=markup&rev=1.1 Index: phpdoc/en/language/control-structures/do-while.xml +++ phpdoc/en/language/control-structures/do-while.xml <?xml version="1.0" encoding="utf-8"?> <!-- $Revision: 1.1 $ --> <sect1 xml:id="control-structures.do.while" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink"> <title><literal>do-while</literal></title> <simpara> <literal>do-while</literal> loops are very similar to <literal>while</literal> loops, except the truth expression is checked at the end of each iteration instead of in the beginning. The main difference from regular <literal>while</literal> loops is that the first iteration of a <literal>do-while</literal> loop is guaranteed to run (the truth expression is only checked at the end of the iteration), whereas it may not necessarily run with a regular <literal>while</literal> loop (the truth expression is checked at the beginning of each iteration, if it evaluates to &false; right from the beginning, the loop execution would end immediately). </simpara> <para> There is just one syntax for <literal>do-while</literal> loops: <informalexample> <programlisting role="php"> <![CDATA[ <?php $i = 0; do { echo $i; } while ($i > 0); ?> ]]> </programlisting> </informalexample> </para> <simpara> The above loop would run one time exactly, since after the first iteration, when truth expression is checked, it evaluates to &false; ($i is not bigger than 0) and the loop execution ends. </simpara> <para> Advanced C users may be familiar with a different usage of the <literal>do-while</literal> loop, to allow stopping execution in the middle of code blocks, by encapsulating them with <literal>do-while</literal> (0), and using the <link linkend="control-structures.break"><literal>break</literal></link> statement. The following code fragment demonstrates this: <informalexample> <programlisting role="php"> <![CDATA[ <?php do { if ($i < 5) { echo "i is not big enough"; break; } $i *= $factor; if ($i < $minimum_limit) { break; } echo "i is ok"; /* process i */ } while (0); ?> ]]> </programlisting> </informalexample> </para> <simpara> Don't worry if you don't understand this right away or at all. You can code scripts and even powerful scripts without using this 'feature'. </simpara> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/viewvc.cgi/phpdoc/en/language/control-structures/else.xml?view=markup&rev=1.1 Index: phpdoc/en/language/control-structures/else.xml +++ phpdoc/en/language/control-structures/else.xml <?xml version="1.0" encoding="utf-8"?> <!-- $Revision: 1.1 $ --> <sect1 xml:id="control-structures.else" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink"> <title><literal>else</literal></title> <para> Often you'd want to execute a statement if a certain condition is met, and a different statement if the condition is not met. This is what <literal>else</literal> is for. <literal>else</literal> extends an <literal>if</literal> statement to execute a statement in case the expression in the <literal>if</literal> statement evaluates to &false;. For example, the following code would display <computeroutput>a is bigger than b</computeroutput> if <varname>$a</varname> is bigger than <varname>$b</varname>, and <computeroutput>a is NOT bigger than b</computeroutput> otherwise: <informalexample> <programlisting role="php"> <![CDATA[ <?php if ($a > $b) { echo "a is bigger than b"; } else { echo "a is NOT bigger than b"; } ?> ]]> </programlisting> </informalexample> The <literal>else</literal> statement is only executed if the <literal>if</literal> expression evaluated to &false;, and if there were any <literal>elseif</literal> expressions - only if they evaluated to &false; as well (see <link linkend="control-structures.elseif">elseif</link>). </para> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/viewvc.cgi/phpdoc/en/language/control-structures/elseif.xml?view=markup&rev=1.1 Index: phpdoc/en/language/control-structures/elseif.xml +++ phpdoc/en/language/control-structures/elseif.xml <?xml version="1.0" encoding="utf-8"?> <!-- $Revision: 1.1 $ --> <sect1 xml:id="control-structures.elseif" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink"> <title><literal>elseif</literal>/<literal>else if</literal></title> <para> <literal>elseif</literal>, as its name suggests, is a combination of <literal>if</literal> and <literal>else</literal>. Like <literal>else</literal>, it extends an <literal>if</literal> statement to execute a different statement in case the original <literal>if</literal> expression evaluates to &false;. However, unlike <literal>else</literal>, it will execute that alternative expression only if the <literal>elseif</literal> conditional expression evaluates to &true;. For example, the following code would display <computeroutput>a is bigger than b</computeroutput>, <computeroutput>a equal to b</computeroutput> or <computeroutput>a is smaller than b</computeroutput>: <informalexample> <programlisting role="php"> <![CDATA[ <?php if ($a > $b) { echo "a is bigger than b"; } elseif ($a == $b) { echo "a is equal to b"; } else { echo "a is smaller than b"; } ?> ]]> </programlisting> </informalexample> </para> <simpara> There may be several <literal>elseif</literal>s within the same <literal>if</literal> statement. The first <literal>elseif</literal> expression (if any) that evaluates to &true; would be executed. In PHP, you can also write 'else if' (in two words) and the behavior would be identical to the one of 'elseif' (in a single word). The syntactic meaning is slightly different (if you're familiar with C, this is the same behavior) but the bottom line is that both would result in exactly the same behavior. </simpara> <simpara> The <literal>elseif</literal> statement is only executed if the preceding <literal>if</literal> expression and any preceding <literal>elseif</literal> expressions evaluated to &false;, and the current <literal>elseif</literal> expression evaluated to &true;. </simpara> <note> <simpara> Note that <literal>elseif</literal> and <literal>else if</literal> will only be considered exactly the same when using curly brackets as in the above example. When using a colon to define your <literal>if</literal>/<literal>elseif</literal> conditions, you must not separate <literal>else if</literal> into two words, or PHP will fail with a parse error. </simpara> </note> <para> <informalexample> <programlisting role="php"> <![CDATA[ <?php /* Incorrect Method: */ if($a > $b): echo $a." is greater than ".$b; else if($a == $b): // Will not compile. echo "The above line causes a parse error."; endif; /* Correct Method: */ if($a > $b): echo $a." is greater than ".$b; elseif($a == $b): // Note the combination of the words. echo $a." equals ".$b; else: echo $a." is neither greater than or equal to ".$b; endif; ?> ]]> </programlisting> </informalexample> </para> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/viewvc.cgi/phpdoc/en/language/control-structures/for.xml?view=markup&rev=1.1 Index: phpdoc/en/language/control-structures/for.xml +++ phpdoc/en/language/control-structures/for.xml <?xml version="1.0" encoding="utf-8"?> <!-- $Revision: 1.1 $ --> <sect1 xml:id="control-structures.for" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink"> <title><literal>for</literal></title> <para> <literal>for</literal> loops are the most complex loops in PHP. They behave like their C counterparts. The syntax of a <literal>for</literal> loop is: <informalexample> <programlisting> <![CDATA[ for (expr1; expr2; expr3) statement ]]> </programlisting> </informalexample> </para> <simpara> The first expression (<varname>expr1</varname>) is evaluated (executed) once unconditionally at the beginning of the loop. </simpara> <simpara> In the beginning of each iteration, <varname>expr2</varname> is evaluated. If it evaluates to &true;, the loop continues and the nested statement(s) are executed. If it evaluates to &false;, the execution of the loop ends. </simpara> <simpara> At the end of each iteration, <varname>expr3</varname> is evaluated (executed). </simpara> <simpara> Each of the expressions can be empty or contain multiple expressions separated by commas. In <varname>expr2</varname>, all expressions separated by a comma are evaluated but the result is taken from the last part. <varname>expr2</varname> being empty means the loop should be run indefinitely (PHP implicitly considers it as &true;, like C). This may not be as useless as you might think, since often you'd want to end the loop using a conditional <link linkend="control-structures.break"><literal>break</literal></link> statement instead of using the <literal>for</literal> truth expression. </simpara> <para> Consider the following examples. All of them display the numbers 1 through 10: <informalexample> <programlisting role="php"> <![CDATA[ <?php /* example 1 */ for ($i = 1; $i <= 10; $i++) { echo $i; } /* example 2 */ for ($i = 1; ; $i++) { if ($i > 10) { break; } echo $i; } /* example 3 */ $i = 1; for (; ; ) { if ($i > 10) { break; } echo $i; $i++; } /* example 4 */ for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++); ?> ]]> </programlisting> </informalexample> </para> <simpara> Of course, the first example appears to be the nicest one (or perhaps the fourth), but you may find that being able to use empty expressions in <literal>for</literal> loops comes in handy in many occasions. </simpara> <para> PHP also supports the alternate "colon syntax" for <literal>for</literal> loops. <informalexample> <programlisting> <![CDATA[ for (expr1; expr2; expr3): statement ... endfor; ]]> </programlisting> </informalexample> </para> <simpara> Its a common thing to many users to iterate though arrays like in the example below. </simpara> <para> <informalexample> <programlisting role="php"> <![CDATA[ <?php /* * This is an array with some data we want to modify * when running through the for loop. */ $people = Array( Array('name' => 'Kalle', 'salt' => 856412), Array('name' => 'Pierre', 'salt' => 215863) ); for($i = 0; $i < sizeof($people); ++$i) { $people[$i]['salt'] = rand(000000, 999999); } ?> ]]> </programlisting> </informalexample> </para> <simpara> The problem lies in the second for expression. This code can be slow because it has to calculate the size of the array on each iteration. Since the size never change, it can be optimized easily using an intermediate variable to store the size and use in the loop instead of sizeof. The example below illustrates this: </simpara> <para> <informalexample> <programlisting role="php"> <![CDATA[ <?php $people = Array( Array('name' => 'Kalle', 'salt' => 856412), Array('name' => 'Pierre', 'salt' => 215863) ); for($i = 0, $size = sizeof($people); $i < $size; ++$i) { $people[$i]['salt'] = rand(000000, 999999); } ?> ]]> </programlisting> </informalexample> </para> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/viewvc.cgi/phpdoc/en/language/control-structures/foreach.xml?view=markup&rev=1.1 Index: phpdoc/en/language/control-structures/foreach.xml +++ phpdoc/en/language/control-structures/foreach.xml <?xml version="1.0" encoding="utf-8"?> <!-- $Revision: 1.1 $ --> <sect1 xml:id="control-structures.foreach" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink"> <title><literal>foreach</literal></title> <para> PHP 4 introduced a <literal>foreach</literal> construct, much like Perl and some other languages. This simply gives an easy way to iterate over arrays. <literal>foreach</literal> works only on arrays, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes; the second is a minor but useful extension of the first: <informalexample> <programlisting> <![CDATA[ foreach (array_expression as $value) statement foreach (array_expression as $key => $value) statement ]]> </programlisting> </informalexample> </para> <simpara> The first form loops over the array given by <literal>array_expression</literal>. On each loop, the value of the current element is assigned to <literal>$value</literal> and the internal array pointer is advanced by one (so on the next loop, you'll be looking at the next element). </simpara> <simpara> The second form does the same thing, except that the current element's key will be assigned to the variable <literal>$key</literal> on each loop. </simpara> <simpara> As of PHP 5, it is possible to <link linkend="language.oop5.iterations">iterate objects</link> too. </simpara> <para> <note> <para> When <literal>foreach</literal> first starts executing, the internal array pointer is automatically reset to the first element of the array. This means that you do not need to call <function>reset</function> before a <literal>foreach</literal> loop. </para> </note> </para> <para> <note> <para> Unless the array is <link linkend="language.references">referenced</link>, <literal>foreach</literal> operates on a copy of the specified array and not the array itself. <literal>foreach</literal> has some side effects on the array pointer. Don't rely on the array pointer during or after the foreach without resetting it. </para> </note> </para> <para> As of PHP 5, you can easily modify array's elements by preceding <literal>$value</literal> with &amp;. This will assign <link linkend="language.references">reference</link> instead of copying the value. <informalexample> <programlisting role="php"> <![CDATA[ <?php $arr = array(1, 2, 3, 4); foreach ($arr as &$value) { $value = $value * 2; } // $arr is now array(2, 4, 6, 8) unset($value); // break the reference with the last element ?> ]]> </programlisting> </informalexample> This is possible only if iterated array can be referenced (i.e. is variable). </para> <warning> <para> Reference of a <literal>$value</literal> and the last array element remain even after the <literal>foreach</literal> loop. It is recommended to destroy it by <function>unset</function>. </para> </warning> <para> <note> <para> <literal>foreach</literal> does not support the ability to suppress error messages using '@'. </para> </note> </para> <para> You may have noticed that the following are functionally identical: <informalexample> <programlisting role="php"> <![CDATA[ <?php $arr = array("one", "two", "three"); reset($arr); while (list(, $value) = each($arr)) { echo "Value: $value<br />\n"; } foreach ($arr as $value) { echo "Value: $value<br />\n"; } ?> ]]> </programlisting> </informalexample> The following are also functionally identical: <informalexample> <programlisting role="php"> <![CDATA[ <?php $arr = array("one", "two", "three"); reset($arr); while (list($key, $value) = each($arr)) { echo "Key: $key; Value: $value<br />\n"; } foreach ($arr as $key => $value) { echo "Key: $key; Value: $value<br />\n"; } ?> ]]> </programlisting> </informalexample> </para> <para> Some more examples to demonstrate usages: <informalexample> <programlisting role="php"> <![CDATA[ <?php /* foreach example 1: value only */ $a = array(1, 2, 3, 17); foreach ($a as $v) { echo "Current value of \$a: $v.\n"; } /* foreach example 2: value (with its manual access notation printed for illustration) */ $a = array(1, 2, 3, 17); $i = 0; /* for illustrative purposes only */ foreach ($a as $v) { echo "\$a[$i] => $v.\n"; $i++; } /* foreach example 3: key and value */ $a = array( "one" => 1, "two" => 2, "three" => 3, "seventeen" => 17 ); foreach ($a as $k => $v) { echo "\$a[$k] => $v.\n"; } /* foreach example 4: multi-dimensional arrays */ $a = array(); $a[0][0] = "a"; $a[0][1] = "b"; $a[1][0] = "y"; $a[1][1] = "z"; foreach ($a as $v1) { foreach ($v1 as $v2) { echo "$v2\n"; } } /* foreach example 5: dynamic arrays */ foreach (array(1, 2, 3, 4, 5) as $v) { echo "$v\n"; } ?> ]]> </programlisting> </informalexample> </para> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/viewvc.cgi/phpdoc/en/language/control-structures/if.xml?view=markup&rev=1.1 Index: phpdoc/en/language/control-structures/if.xml +++ phpdoc/en/language/control-structures/if.xml <?xml version="1.0" encoding="utf-8"?> <!-- $Revision: 1.1 $ --> <sect1 xml:id="control-structures.if" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink"> <title><literal>if</literal></title> <para> The <literal>if</literal> construct is one of the most important features of many languages, PHP included. It allows for conditional execution of code fragments. PHP features an <literal>if</literal> structure that is similar to that of C: <informalexample> <programlisting> <![CDATA[ if (expr) statement ]]> </programlisting> </informalexample> </para> <simpara> As described in <link linkend="language.expressions">the section about expressions</link>, <replaceable>expression</replaceable> is evaluated to its Boolean value. If <replaceable>expression</replaceable> evaluates to &true;, PHP will execute <replaceable>statement</replaceable>, and if it evaluates to &false; - it'll ignore it. More information about what values evaluate to &false; can be found in the <link linkend="language.types.boolean.casting">'Converting to boolean'</link> section. </simpara> <para> The following example would display <computeroutput>a is bigger than b</computeroutput> if <varname>$a</varname> is bigger than <varname>$b</varname>: <informalexample> <programlisting role="php"> <![CDATA[ <?php if ($a > $b) echo "a is bigger than b"; ?> ]]> </programlisting> </informalexample> </para> <para> Often you'd want to have more than one statement to be executed conditionally. Of course, there's no need to wrap each statement with an <literal>if</literal> clause. Instead, you can group several statements into a statement group. For example, this code would display <computeroutput>a is bigger than b</computeroutput> if <varname>$a</varname> is bigger than <varname>$b</varname>, and would then assign the value of <varname>$a</varname> into <varname>$b</varname>: <informalexample> <programlisting role="php"> <![CDATA[ <?php if ($a > $b) { echo "a is bigger than b"; $b = $a; } ?> ]]> </programlisting> </informalexample> </para> <simpara> <literal>If</literal> statements can be nested infinitely within other <literal>if</literal> statements, which provides you with complete flexibility for conditional execution of the various parts of your program. </simpara> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/viewvc.cgi/phpdoc/en/language/control-structures/include-once.xml?view=markup&rev=1.1 Index: phpdoc/en/language/control-structures/include-once.xml +++ phpdoc/en/language/control-structures/include-once.xml <?xml version="1.0" encoding="utf-8"?> <!-- $Revision: 1.1 $ --> <sect1 xml:id="function.include-once" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink"> <title><function>include_once</function></title> <para> The <function>include_once</function> statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the <function>include</function> statement, with the only difference being that if the code from a file has already been included, it will not be included again. As the name suggests, it will be included just once. </para> <para> <function>include_once</function> should be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, and you want to be sure that it is included exactly once to avoid problems with function redefinitions, variable value reassignments, etc. </para> <para> For more examples on using <function>require_once</function> and <function>include_once</function>, look at the <link xlink:href="&url.php.pear;">PEAR</link> code included in the latest PHP source code distributions. </para> <para> Return values are the same as with <function>include</function>. If the file was already included, this function returns &true; </para> <para> <note> <para> <function>include_once</function> was added in PHP 4.0.1 </para> </note> </para> <para> <note> <para> Be aware, that the behaviour of <function>include_once</function> and <function>require_once</function> may not be what you expect on a non case sensitive operating system (such as Windows). <example> <title><function>include_once</function> is case insensitive on Windows</title> <programlisting role="php"> <![CDATA[ <?php include_once "a.php"; // this will include a.php include_once "A.php"; // this will include a.php again on Windows! (PHP 4 only) ?> ]]> </programlisting> </example> This behaviour changed in PHP 5 - the path is normalized first so that <filename>C:\PROGRA~1\A.php</filename> is realized the same as <filename>C:\Program Files\a.php</filename> and the file is included just once. </para> </note> </para> &warn.no-win32-fopen-wrapper; <para> See also <function>include</function>, <function>require</function>, <function>require_once</function>, <function>get_required_files</function>, <function>get_included_files</function>, <function>readfile</function>, and <function>virtual</function>. </para> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/viewvc.cgi/phpdoc/en/language/control-structures/include.xml?view=markup&rev=1.1 Index: phpdoc/en/language/control-structures/include.xml +++ phpdoc/en/language/control-structures/include.xml <?xml version="1.0" encoding="utf-8"?> <!-- $Revision: 1.1 $ --> <sect1 xml:id="function.include" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink"> <title><function>include</function></title> <simpara> The <function>include</function> statement includes and evaluates the specified file. </simpara> <simpara> The documentation below also applies to <function>require</function>. The two constructs are identical in every way except how they handle failure. They both produce a <link linkend="errorfunc.constants.errorlevels.e-warning">Warning</link>, but <function>require</function> results in a <link linkend="errorfunc.constants.errorlevels.e-error">Fatal Error</link>. In other words, use <function>require</function> if you want a missing file to halt processing of the page. <function>include</function> does not behave this way, the script will continue regardless. Be sure to have an appropriate <link linkend="ini.include-path">include_path</link> setting as well. Be warned that parse error in included file doesn't cause processing halting in PHP versions prior to PHP 4.3.5. Since this version, it does. </simpara> <simpara> Files for including are first looked for in each include_path entry relative to the current working directory, and then in the directory of current script. E.g. if your include_path is <literal>libraries</literal>, current working directory is <filename class="directory">/www/</filename>, you included <filename>include/a.php</filename> and there is <literal>include "b.php"</literal> in that file, <filename>b.php</filename> is first looked in <filename class="directory">/www/libraries/</filename> and then in <filename class="directory">/www/include/</filename>. If filename begins with <literal>./</literal> or <literal>../</literal>, it is looked only in the current working directory. </simpara> <simpara> When a file is included, the code it contains inherits the <link linkend="language.variables.scope">variable scope</link> of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope. </simpara> <para> <example> <title>Basic <function>include</function> example</title> <programlisting role="php"> <![CDATA[ vars.php <?php $color = 'green'; $fruit = 'apple'; ?> test.php <?php echo "A $color $fruit"; // A include 'vars.php'; echo "A $color $fruit"; // A green apple ?> ]]> </programlisting> </example> </para> <simpara> If the include occurs inside a function within the calling file, then all of the code contained in the called file will behave as though it had been defined inside that function. So, it will follow the variable scope of that function. An exception to this rule are <link linkend="language.constants.predefined">magic constants</link> which are evaluated by the parser before the include occurs. </simpara> <para> <example> <title>Including within functions</title> <programlisting role="php"> <![CDATA[ <?php function foo() { global $color; include 'vars.php'; echo "A $color $fruit"; } /* vars.php is in the scope of foo() so * * $fruit is NOT available outside of this * * scope. $color is because we declared it * * as global. */ foo(); // A green apple echo "A $color $fruit"; // A green ?> ]]> </programlisting> </example> </para> <simpara> When a file is included, parsing drops out of PHP mode and into HTML mode at the beginning of the target file, and resumes again at the end. For this reason, any code inside the target file which should be executed as PHP code must be enclosed within <link linkend="language.basic-syntax.phpmode">valid PHP start and end tags</link>. </simpara> <simpara> If "<link linkend="ini.allow-url-fopen">URL fopen wrappers</link>" are enabled in PHP (which they are in the default configuration), you can specify the file to be included using a URL (via HTTP or other supported wrapper - see <xref linkend="wrappers"/> for a list of protocols) instead of a local pathname. If the target server interprets the target file as PHP code, variables may be passed to the included file using a URL request string as used with HTTP GET. This is not strictly speaking the same thing as including the file and having it inherit the parent file's variable scope; the script is actually being run on the remote server and the result is then being included into the local script. </simpara> &warn.no-win32-fopen-wrapper; <para> <example> <title><function>include</function> through HTTP</title> <programlisting role="php"> <![CDATA[ <?php /* This example assumes that www.example.com is configured to parse .php * files and not .txt files. Also, 'Works' here means that the variables * $foo and $bar are available within the included file. */ // Won't work; file.txt wasn't handled by www.example.com as PHP include 'http://www.example.com/file.txt?foo=1&bar=2'; // Won't work; looks for a file named 'file.php?foo=1&bar=2' on the // local filesystem. include 'file.php?foo=1&bar=2'; // Works. include 'http://www.example.com/file.php?foo=1&bar=2'; $foo = 1; $bar = 2; include 'file.txt'; // Works. include 'file.php'; // Works. ?> ]]> </programlisting> </example> </para> <warning> <title>Security warning</title> <para> Remote file may be processed at the remote server (depending on the file extension and the fact if the remote server runs PHP or not) but it still has to produce a valid PHP script because it will be processed at the local server. If the file from the remote server should be processed there and outputted only, <function>readfile</function> is much better function to use. Otherwise, special care should be taken to secure the remote script to produce a valid and desired code. </para> </warning> <para> See also <link linkend="features.remote-files">Remote files</link>, <function>fopen</function> and <function>file</function> for related information. </para> <simpara> Handling Returns: It is possible to execute a <function>return</function> statement inside an included file in order to terminate processing in that file and return to the script which called it. Also, it's possible to return values from included files. You can take the value of the include call as you would a normal function. This is not, however, possible when including remote files unless the output of the remote file has <link linkend="language.basic-syntax.phpmode">valid PHP start and end tags</link> (as with any local file). You can declare the needed variables within those tags and they will be introduced at whichever point the file was included. </simpara> <para> Because <function>include</function> is a special language construct, parentheses are not needed around its argument. Take care when comparing return value. <example> <title>Comparing return value of include</title> <programlisting role="php"> <![CDATA[ <?php // won't work, evaluated as include(('vars.php') == 'OK'), i.e. include('') if (include('vars.php') == 'OK') { echo 'OK'; } // works if ((include 'vars.php') == 'OK') { echo 'OK'; } ?> ]]> </programlisting> </example> </para> <para> <example> <title><function>include</function> and the <function>return</function> statement</title> <programlisting role="php"> <![CDATA[ return.php <?php $var = 'PHP'; return $var; ?> noreturn.php <?php $var = 'PHP'; ?> testreturns.php <?php $foo = include 'return.php'; echo $foo; // prints 'PHP' $bar = include 'noreturn.php'; echo $bar; // prints 1 ?> ]]> </programlisting> </example> </para> <simpara> <literal>$bar</literal> is the value <literal>1</literal> because the include was successful. Notice the difference between the above examples. The first uses <function>return</function> within the included file while the other does not. If the file can't be included, &false; is returned and <literal>E_WARNING</literal> is issued. </simpara> <para> If there are functions defined in the included file, they can be used in the main file independent if they are before <function>return</function> or after. If the file is included twice, PHP 5 issues fatal error because functions were already declared, while PHP 4 doesn't complain about functions defined after <function>return</function>. It is recommended to use <function>include_once</function> instead of checking if the file was already included and conditionally return inside the included file. </para> <simpara> Another way to "include" a PHP file into a variable is to capture the output by using the <link linkend="ref.outcontrol">Output Control Functions</link> with <function>include</function>. For example: </simpara> <para> <example> <title>Using output buffering to include a PHP file into a string</title> <programlisting role="php"> <![CDATA[ <?php $string = get_include_contents('somefile.php'); function get_include_contents($filename) { if (is_file($filename)) { ob_start(); include $filename; $contents = ob_get_contents(); ob_end_clean(); return $contents; } return false; } ?> ]]> </programlisting> </example> </para> <para> In order to automatically include files within scripts, see also the <link linkend="ini.auto-prepend-file">auto_prepend_file</link> and <link linkend="ini.auto-append-file">auto_append_file</link> configuration options in &php.ini;. </para> &note.language-construct; <simpara> See also <function>require</function>, <function>require_once</function>, <function>include_once</function>, <function>get_included_files</function>, <function>readfile</function>, <function>virtual</function>, and <link linkend="ini.include-path">include_path</link>. </simpara> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/viewvc.cgi/phpdoc/en/language/control-structures/require-once.xml?view=markup&rev=1.1 Index: phpdoc/en/language/control-structures/require-once.xml +++ phpdoc/en/language/control-structures/require-once.xml <?xml version="1.0" encoding="utf-8"?> <!-- $Revision: 1.1 $ --> <sect1 xml:id="function.require-once" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink"> <title><function>require_once</function></title> <para> The <function>require_once</function> statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the <function>require</function> statement, with the only difference being that if the code from a file has already been included, it will not be included again. See the documentation for <function>require</function> for more information on how this statement works. </para> <para> <function>require_once</function> should be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, and you want to be sure that it is included exactly once to avoid problems with function redefinitions, variable value reassignments, etc. </para> <para> For examples on using <function>require_once</function> and <function>include_once</function>, look at the <link xlink:href="&url.php.pear;">PEAR</link> code included in the latest PHP source code distributions. </para> <para> Return values are the same as with <function>include</function>. If the file was already included, this function returns &true; </para> <para> <note> <para> <function>require_once</function> was added in PHP 4.0.1 </para> </note> </para> <para> <note> <para> Be aware, that the behaviour of <function>require_once</function> and <function>include_once</function> may not be what you expect on a non case sensitive operating system (such as Windows). <example> <title><function>require_once</function> is case insensitive on Windows</title> <programlisting role="php"> <![CDATA[ <?php require_once "a.php"; // this will include a.php require_once "A.php"; // this will include a.php again on Windows! (PHP 4 only) ?> ]]> </programlisting> </example> This behaviour changed in PHP 5 - the path is normalized first so that <filename>C:\PROGRA~1\A.php</filename> is realized the same as <filename>C:\Program Files\a.php</filename> and the file is required just once. </para> </note> </para> &warn.no-win32-fopen-wrapper; <para> See also <function>require</function>, <function>include</function>, <function>include_once</function>, <function>get_required_files</function>, <function>get_included_files</function>, <function>readfile</function>, and <function>virtual</function>. </para> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/viewvc.cgi/phpdoc/en/language/control-structures/require.xml?view=markup&rev=1.1 Index: phpdoc/en/language/control-structures/require.xml +++ phpdoc/en/language/control-structures/require.xml <?xml version="1.0" encoding="utf-8"?> <!-- $Revision: 1.1 $ --> <sect1 xml:id="function.require" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink"> <title><function>require</function></title> <simpara> The <function>require</function> statement includes and evaluates the specific file. </simpara> <simpara> <function>require</function> includes and evaluates a specific file. Detailed information on how this inclusion works is described in the documentation for <function>include</function>. </simpara> <simpara> <function>require</function> and <function>include</function> are identical in every way except how they handle failure. They both produce a <link linkend="errorfunc.constants.errorlevels.e-warning">Warning</link>, but <function>require</function> results in a <link linkend="errorfunc.constants.errorlevels.e-error"> Fatal Error</link>. In other words, don't hesitate to use <function>require</function> if you want a missing file to halt processing of the page. <function>include</function> does not behave this way, the script will continue regardless. Be sure to have an appropriate <link linkend="ini.include-path">include_path</link> setting as well. </simpara> <para> <example> <title>Basic <function>require</function> examples</title> <programlisting role="php"> <![CDATA[ <?php require 'prepend.php'; require $somefile; require ('somefile.txt'); ?> ]]> </programlisting> </example> </para> <simpara> See the <function>include</function> documentation for more examples. </simpara> <para> <note> <simpara> Prior to PHP 4.0.2, the following applies: <function>require</function> will always attempt to read the target file, even if the line it's on never executes. The conditional statement won't affect <function>require</function>. However, if the line on which the <function>require</function> occurs is not executed, neither will any of the code in the target file be executed. Similarly, looping structures do not affect the behaviour of <function>require</function>. Although the code contained in the target file is still subject to the loop, the <function>require</function> itself happens only once. </simpara> </note> </para> &note.language-construct; &warn.no-win32-fopen-wrapper; <simpara> See also <function>include</function>, <function>require_once</function>, <function>include_once</function>, <function>get_included_files</function>, <function>eval</function>, <function>file</function>, <function>readfile</function>, <function>virtual</function> and <link linkend="ini.include-path">include_path</link>. </simpara> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/viewvc.cgi/phpdoc/en/language/control-structures/return.xml?view=markup&rev=1.1 Index: phpdoc/en/language/control-structures/return.xml +++ phpdoc/en/language/control-structures/return.xml <?xml version="1.0" encoding="utf-8"?> <!-- $Revision: 1.1 $ --> <sect1 xml:id="function.return" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink"> <title>return</title> <simpara> If called from within a function, the <function>return</function> statement immediately ends execution of the current function, and returns its argument as the value of the function call. <function>return</function> will also end the execution of an <function>eval</function> statement or script file. </simpara> <simpara> If called from the global scope, then execution of the current script file is ended. If the current script file was <function>include</function>ed or <function>require</function>ed, then control is passed back to the calling file. Furthermore, if the current script file was <function>include</function>ed, then the value given to <function>return</function> will be returned as the value of the <function>include</function> call. If <function>return</function> is called from within the main script file, then script execution ends. If the current script file was named by the <link linkend="ini.auto-prepend-file">auto_prepend_file</link> or <link linkend="ini.auto-append-file">auto_append_file</link> configuration options in &php.ini;, then that script file's execution is ended. </simpara> <simpara>For more information, see <link linkend="functions.returning-values">Returning values</link>. </simpara> <para> <note> <simpara> Note that since <function>return</function> is a language construct and not a function, the parentheses surrounding its arguments are not required. It is common to leave them out, and you actually should do so as PHP has less work to do in this case. </simpara> </note> <note> <simpara> You should <emphasis>never</emphasis> use parentheses around your return variable when returning by reference, as this will not work. You can only return variables by reference, not the result of a statement. If you use <literal>return ($a);</literal> then you're not returning a variable, but the result of the expression <literal>($a)</literal> (which is, of course, the value of <varname>$a</varname>). </simpara> </note> </para> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/viewvc.cgi/phpdoc/en/language/control-structures/switch.xml?view=markup&rev=1.1 Index: phpdoc/en/language/control-structures/switch.xml +++ phpdoc/en/language/control-structures/switch.xml <?xml version="1.0" encoding="utf-8"?> <!-- $Revision: 1.1 $ --> <sect1 xml:id="control-structures.switch" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink"> <title><literal>switch</literal></title> <simpara> The <literal>switch</literal> statement is similar to a series of IF statements on the same expression. In many occasions, you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to. This is exactly what the <literal>switch</literal> statement is for. </simpara> <note> <simpara> Note that unlike some other languages, the <link linkend="control-structures.continue">continue</link> statement applies to switch and acts similar to <literal>break</literal>. If you have a switch inside a loop and wish to continue to the next iteration of the outer loop, use <literal>continue 2</literal>. </simpara> </note> <note> <para> Note that switch/case does <link linkend="types.comparisions-loose">loose comparision</link>. </para> </note> <para> The following two examples are two different ways to write the same thing, one using a series of <literal>if</literal> and <literal>elseif</literal> statements, and the other using the <literal>switch</literal> statement: <example> <title><literal>switch</literal> structure</title> <programlisting role="php"> <![CDATA[ <?php if ($i == 0) { echo "i equals 0"; } elseif ($i == 1) { echo "i equals 1"; } elseif ($i == 2) { echo "i equals 2"; } switch ($i) { case 0: echo "i equals 0"; break; case 1: echo "i equals 1"; break; case 2: echo "i equals 2"; break; } ?> ]]> </programlisting> </example> <example> <title><literal>switch</literal> structure allows usage of strings</title> <programlisting role="php"> <![CDATA[ <?php switch ($i) { case "apple": echo "i is apple"; break; case "bar": echo "i is bar"; break; case "cake": echo "i is cake"; break; } ?> ]]> </programlisting> </example> </para> <para> It is important to understand how the <literal>switch</literal> statement is executed in order to avoid mistakes. The <literal>switch</literal> statement executes line by line (actually, statement by statement). In the beginning, no code is executed. Only when a <literal>case</literal> statement is found with a value that matches the value of the <literal>switch</literal> expression does PHP begin to execute the statements. PHP continues to execute the statements until the end of the <literal>switch</literal> block, or the first time it sees a <literal>break</literal> statement. If you don't write a <literal>break</literal> statement at the end of a case's statement list, PHP will go on executing the statements of the following case. For example: <informalexample> <programlisting role="php"> <![CDATA[ <?php switch ($i) { case 0: echo "i equals 0"; case 1: echo "i equals 1"; case 2: echo "i equals 2"; } ?> ]]> </programlisting> </informalexample> </para> <simpara> Here, if <varname>$i</varname> is equal to 0, PHP would execute all of the echo statements! If <varname>$i</varname> is equal to 1, PHP would execute the last two echo statements. You would get the expected behavior ('i equals 2' would be displayed) only if <varname>$i</varname> is equal to 2. Thus, it is important not to forget <literal>break</literal> statements (even though you may want to avoid supplying them on purpose under certain circumstances). </simpara> <simpara> In a <literal>switch</literal> statement, the condition is evaluated only once and the result is compared to each <literal>case</literal> statement. In an <literal>elseif</literal> statement, the condition is evaluated again. If your condition is more complicated than a simple compare and/or is in a tight loop, a <literal>switch</literal> may be faster. </simpara> <para> The statement list for a case can also be empty, which simply passes control into the statement list for the next case. <informalexample> <programlisting role="php"> <![CDATA[ <?php switch ($i) { case 0: case 1: case 2: echo "i is less than 3 but not negative"; break; case 3: echo "i is 3"; } ?> ]]> </programlisting> </informalexample> </para> <para> A special case is the <literal>default</literal> case. This case matches anything that wasn't matched by the other cases. For example: <informalexample> <programlisting role="php"> <![CDATA[ <?php switch ($i) { case 0: echo "i equals 0"; break; case 1: echo "i equals 1"; break; case 2: echo "i equals 2"; break; default: echo "i is not equal to 0, 1 or 2"; } ?> ]]> </programlisting> </informalexample> </para> <para> The <literal>case</literal> expression may be any expression that evaluates to a simple type, that is, integer or floating-point numbers and strings. Arrays or objects cannot be used here unless they are dereferenced to a simple type. </para> <para> The alternative syntax for control structures is supported with switches. For more information, see <link linkend="control-structures.alternative-syntax">Alternative syntax for control structures</link>. <informalexample> <programlisting role="php"> <![CDATA[ <?php switch ($i): case 0: echo "i equals 0"; break; case 1: echo "i equals 1"; break; case 2: echo "i equals 2"; break; default: echo "i is not equal to 0, 1 or 2"; endswitch; ?> ]]> </programlisting> </informalexample> </para> <para> Its possible to use a semicolon instead of a colon after a case like: <informalexample> <programlisting role="php"> <![CDATA[ <?php switch($beer) { case 'tuborg'; case 'carlsberg'; case 'heineken'; echo 'Good choice'; break; default; echo 'Please make a new selection...'; break; } ?> ]]> </programlisting> </informalexample> </para> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/viewvc.cgi/phpdoc/en/language/control-structures/while.xml?view=markup&rev=1.1 Index: phpdoc/en/language/control-structures/while.xml +++ phpdoc/en/language/control-structures/while.xml <?xml version="1.0" encoding="utf-8"?> <!-- $Revision: 1.1 $ --> <sect1 xml:id="control-structures.while" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink"> <title><literal>while</literal></title> <para> <literal>while</literal> loops are the simplest type of loop in PHP. They behave just like their C counterparts. The basic form of a <literal>while</literal> statement is: <informalexample> <programlisting> <![CDATA[ while (expr) statement ]]> </programlisting> </informalexample> </para> <simpara> The meaning of a <literal>while</literal> statement is simple. It tells PHP to execute the nested statement(s) repeatedly, as long as the <literal>while</literal> expression evaluates to &true;. The value of the expression is checked each time at the beginning of the loop, so even if this value changes during the execution of the nested statement(s), execution will not stop until the end of the iteration (each time PHP runs the statements in the loop is one iteration). Sometimes, if the <literal>while</literal> expression evaluates to &false; from the very beginning, the nested statement(s) won't even be run once. </simpara> <para> Like with the <literal>if</literal> statement, you can group multiple statements within the same <literal>while</literal> loop by surrounding a group of statements with curly braces, or by using the alternate syntax: <informalexample> <programlisting> <![CDATA[ while (expr): statement ... endwhile; ]]> </programlisting> </informalexample> </para> <para> The following examples are identical, and both print the numbers 1 through 10: <informalexample> <programlisting role="php"> <![CDATA[ <?php /* example 1 */ $i = 1; while ($i <= 10) { echo $i++; /* the printed value would be $i before the increment (post-increment) */ } /* example 2 */ $i = 1; while ($i <= 10): echo $i; $i++; endwhile; ?> ]]> </programlisting> </informalexample> </para> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 -->
« previous php.doc.cvs (#2838) next »