PHP 3
Constants, Arrays, Loops
Constants
• Cannot be changed• Are used without $
define ($name, $value [, $case_sen])
<?phpdefine ("text", “Hello from PHP!");define ("num", 10);$result = num*5;echo text; echo "<br />$result";
?>
Arrays
An array in PHP is actually an ordered map. A map is a type that maps values to keys. This type is optimized in several ways, so you can use it as a real array, or a list (vector), hashtable (which is an implementation of a map), dictionary, collection, stack, queue and probably more. Because you can have another PHP-array as a value, you can also quite easily simulate trees.
Arrays
• An array can be created by the array() language-construct. It takes a certain number of comma-separated key => value pairs.
• A key is either an integer or a string.• If you omit a key, the maximum of the integer-
indices is taken, and the new key will be that maximum + 1.
array( [key =>] value , ... ) array("foo" => "bar", 12 => true);
Arrays
• $color = array ('red', 'black', 'white', 'blue', 'green');• $style = array ( 'color' => 'Red', 'size' => '10px‘ );
• // This array is the same as ...
array(5 => 43, 32, 56, "b" => 12);
// ...this array
array(5 => 43, 6 => 32, 7 => 56, "b" => 12);
Arrays: multidimensional
$book = array (/* $book[0] */array ('name' => 'Vasia', 'family' => 'Petrov', 'phone' => '11-11-11'),/* $book[1] */array ('name' => 'Petia', 'family' => 'Sidorov', 'phone' => '22-22-22'),/* $book[2] */array ('name' => 'Andrey', 'family' => 'Ivanov', 'phone' => '33-33-33'));
Arrays: Creating/modifying
$arr[key] = value; - set value (add/change)$arr[] = value; - add new value to the end
• If $arr doesn't exist yet, it will be created
unset($arr[5]); - remove elementunset($arr); - delete array
count($array).count($array)-1.
Loops
• while - loops through a block of code as long as a specified condition is true
• do...while - loops through a block of code once, and then repeats the loop as long as a special condition is true
• for - loops through a block of code a specified number of times
• foreach -
The while Statement
while (condition) code to be executed;
<?php $i=1; while($i<=5) {
echo "The number is " . $i . "<br />"; $i++;
} ?>
The do...while Statement
do {
code to be executed; } while (condition);
The for Statement
for (initialization; condition; increment)
{ code to be executed; }
<?php
for ($i=1; $i<=5; $i++)
{
echo "Hello World!<br />";
}
?>
The foreach Statement
<?php $string = 'We have a string'; $array = explode(" ",$string); foreach($array as $value)
echo $value . '<br />'; ?>
Loops
• break ends execution of the current for, foreach while, do..while or switch structure.
• continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the beginning of the next iteration.
Top Related