Lecture Silde 25-54
Lecture Silde 25-54
$x = 2;
while ($x < 1000) {
echo $x . “n”; // \n is newline character
$x = $x * $x;
}
Value of $x $x < 1000? Result
2 TRUE prints 2
4 TRUE prints 4
16 TRUE prints 16
256 TRUE prints 256
65536 FALSE exits loop
The do-while loop
The code within the loop is executed at least once,
regardless of whether the condition is true
do {
statements
} while (condition);
equivalent to:
statements
while (condition) {
statements
}
The for loop
for (init; condition; increment) {
statements
}
equivalent to:
init
while (condition) {
statements
increment
}
function function1() {
… // some code
function3(); // makes function call to function3()
}
function function2() { // this function is never called!
… // some code
}
function function3() {
… // some code
}
?>
Variable scope
Variables declared within a function have local scope
Can only be accessed from within the function
<?php
function function1() {
… // some code
$local_var = 5; // this variable is LOCAL to
// function1()
echo $local_var + 3; // prints 8
}
… // some code
function1();
echo $local_var; // does nothing, since $local_var is
// out of scope
?>
Global variable scope
Variables declared outside a function have global
scope
Must use global keyword to gain access within functions
<?php
function function1() {
echo $a; // does nothing, $a is out of scope
global $a; // gain access to $a within function
echo $a; // prints 4
}
… // some code
$a = 4; // $a is a global variable
function1();
?>
PHP
Syntax: Arrays
Arrays as a list of elements
Use arrays to keep track of a list of elements using
the same variable name, identifying each element by
its index, starting with 0
$colors = array(‘red’, ‘blue’, ‘green’, ‘black’, ‘yellow’);
print_r($colors) gives:
Array(
[0] => red
[1] => blue
[2] => green
[3] => black
[4] => yellow
)
Turns out all arrays in PHP are associative arrays
🞑 In the example above, keys were simply the index into the list
Each element in an array will have a unique key, whether you
specify it or not.
Specifying the key/index
Thus, we can add to a list of elements with any
arbitrary index
🞑 Usingan index that already existswill overwrite the
value
$colors = array(‘red’, ‘blue’, ‘green’, ‘black’, ‘yellow’);
$colors[5] = ‘gray’; // the next element is gray
$colors[8] = ‘pink’;// not the next index, works anyways
$colors[7] = ‘orange’ // out of order works as well
Array functions
isset($array_name[$key_value]) tells whether a variable
is set, which means that it has to be declared and is not NULL.
unset($array_name[$key_value]) removes the key-value
mapping associated with $key_value in the array
🞑 The unset() function does not “re-index” and will leave
<html>
<head><title>This is welcome.php</title></head>
<body>
The name that was submitted was:
<?php echo $_POST['name']; ?><br />
The phone number that was submitted was:
<?php echo $_POST['phone']; ?><br />
</body>
</html>