Lab06-php03 V1.01 ---updated
Lab06-php03 V1.01 ---updated
Lab06-php03 V1.01 ---updated
Php
Arrays
2. Key/Value – array
<?php
$stuff = array("name" => “Chew",
"course" => “Web Application");
echo $stuff["course"], "\n";
?>
echo("<pre>\n");
print_r($stuff);
echo("\n</pre>\n");
var_dump($stuff);
4. For loop, to loop through array.
<?php
$stuff = array(“Chew",“WebApp");
for($i=0; $i < count($stuff); $i++) {
echo "I=",$i," Val=",$stuff[$i],"\n";
}
?>
5. Task
- Create an array to store at least 4 items. (e.g., banana, apple, pineapple, mango).
- Use a loop (for or while), to loop through the array and print the item.
Super Global $_GET (Array)
Php – end of url parameters into a global variable name $_GET
1. Try out the following code to dump out the variable from url parameters.
2. Access the php code above through the url from the localhost, type in your name as
one of the parameters in the url, observe whether your name has been printed on the
browser.
- Observe that the code will dump the parameters in an array.
- The parameters will be stored in a global variable $_GET. Screenshot the output
Functions
Reference: https://www.php.net/manual/en/ref.strings.php
Reference: https://www.w3schools.com/php/php_string.asp
2. Use str built in function to calculate the length of your full name. Screenshot the
output
function greet() {
print "Hello\n";
}
greet();
greet();
4. Write the following for loops in a function. Call the function for at least 2 times.
Screenshot the output.
function double($alias) {
$alias = $alias * 2;
return $alias;
}
$val = 10;
$dval = double($val);
echo "Value = $val Doubled = $dval\n";
2. Call by reference. Understand the difference between call by value and call by
reference.
function triple(&$realthing) {
$realthing = $realthing * 3;
}
$val = 10;
triple($val);
echo "Triple = $val\n";
Optional: Function
function greeting() {
return "Hello";
}
print greeting() . " Glenn\n";
print greeting() . " Sally\n";
2. Using the basic return function given above, store the return value of function into a
variable, and print the variable out on a browser.
function howdy($lang='es') {
if ( $lang == 'es' ) return "Hola";
if ( $lang == 'fr' ) return "Bonjour";
return "Hello";
}
print howdy('es') . " Glenn\n";
print howdy('fr') . " Sally\n";
4. Using the function given in the previous section. Add an additional language (e.g,.
Chinese). Then call the function to print it out on to the browser.
Optional: Global Variable
1. Normal scope.
function tryzap() {
$val = 100;
}
$val = 10;
tryzap();
echo "TryZap = $val\n";
2. Global scope
function dozap() {
global $val;
$val = 100;
}
$val = 10;
dozap();
echo "DoZap = $val\n";
3. Try out the code, and try to understand how does a global variable work.