CS174
Chris Pollett
Feb 24, 2016
On Monday, we started introducing the PHP language. We learned a little about its history and configuration. We also learned about its copy and interpretive mode, its types, literals, operators, and outputing mechanisms. Today, we start by looking at some of its control structures.
//if if($a) print "hello"; //switch case: switch($a) { case 5: echo "hello"; }
for($a = 0; $a<10; $a++){echo "hello $a";}
while(!$var) { /*do something*/}
do {/*do something */} while (!$var);
<?php if ($the_world_is_round == true): ?> The word is not flat. <?php endif; ?>
$a = array("hi", 1, 2); //for PHP >= 5.4 you can also use the syntax: $a = ["hi", 1, 2];
$b = ["hi", [1,2], 2]; $c = ["a" => "c"];
echo $a[0]." ".$c['a'];
foreach($arr as $var){echo $var;} foreach($assoc_arr as $key => $value){echo "Key $key Value $value";}
list($first, $second, ) = $arr; //$first will be $arr[0], $second will be $arr[1].
$arr = [0=> 1, 1=>2, 2=>3];
$arr = ["joe"=> 5, "mary" =>6];
$keys = array_keys($arr) and $values = array_values($arr);
$barr[1] = 5; // creates array $barr if doesn't exist
$str="this is a string"; $words = explode(" ", $str); /*make an array of tokens of items between consecutive spaces. So words is the array ["this", "is", "a", "string"]. */ $str2 = implode(" ", $words); //undoes the explode.
$cities = ["San Jose", "San Diego"]; echo current($cities); // prints San Jose $another = next($cities); // $another is now San Diego;
function name([parameter]){...}
function inc($i){return ++$i;}
$b = inc($a); // leaves the value of $a unchanged
$b =inc(&$a); //here the value of $a is changed (one is added to it).
$bob = 5; function test() { $bob = 6; echo $bob; //echo's 6 } test(); echo $bob; //echo's 5
$bob = 5; function test() { global $bob; # if did not do bob would be NULL echo $bob; } test();PHP also supports static local variables. These preserve states between function calls:
function addone () {static $count =0; echo $count++;}
$fruits = preg_split("/\s+/", "apples oranges banana");would split on one or more white space characters.
<form method="get" action="script.php"> <input type="text" name="my_textfield" size="10" /> <input type="hidden" name="secret_data" value="do not peak" /> <input type="submit" name="sendform" value="Send this Form" /> </form>
script.php?my_textfield=hello&secret_data=do%20not%20peak&sendform=Send%20this%20Form
<form method="post" action="script.php" enctype="multipart/form-data"> <input type="file" name="my_file" />...</form>
<?php function messageController() { //decide which view to use and set up data for output } function formView($data) { // $data has any data set up from the controller //outputs the message form } function seenWordsView($data) { //outputs seen words, allowed a foreach loop and to //echo variables. Not allowed to call preg_ functions or explode } messageController();