CS267
Chris Pollett
Sep 9, 2019
Consider the file test.php:
hello world <?php echo "hello world"; ?> yeah!! <?php echo "okay";
If we ran this from the command line using:
php test.php
This would output:
hello world hello worldyeah!! okay
<?php function foo() { echo "hi"; } foo(); // prints hi
short_open_tag = Onso that you can escape to a PHP script using <? rather than <?php
;error_reporting = E_ALL & ~E_NOTICEand uncomment it, restart Apache
You can see what PHP's configuration settings are in use by the following small program
<?php phpinfo();
$a = 53; $b = $a + 1;
//if if($a) print "hello"; //switch case: switch($a) { case 5: echo "hello"; break; }
for($a = 0; $a<10; $a++){echo "hello $a";}
while(!$var) { /*do something*/}
do {/*do something */} while (!$var);
$a = array("hi", 1, 2); //for PHP >= 5.4 you can also use the syntax: $a = ["hi", 1, 2]; //what to use in all modern code
$b = ["hi", [1,2], 2]; $c = ["a" => "c"]; // key => value associative array
echo $a[0]." ".$c['a']; //$c['a'] returns "c"
foreach($arr as $var) {echo $var;} foreach($assoc_arr as $key => $value) {echo "Key $key Value $value";}
[0=>1, 1=>2, 2=>3]
$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); /*acts like split except here the first argument is a string rather than a regular expression. So words is an array("this", "is", "a", "string"). PHP has a split function but not as fast, since arg might be a regular expression. */ $str2 = implode(" ", $words); //undoes the explode.
function name([parameter list]){...}
function inc($i){return ++$i;}
$b = inc($a); // leaves the value of $a unchanged
function inc(&$i){...}
Which of the following is true?
$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++;}
$foo_files = glob("./foo*"); /* return an array of file names in the current directory that begin with foo */
$fileHandle = fopen("my.dat", "r"); // r is for reading, w is for writing, etc $file_string = fread($fileHandle, filesize("my.dat")); //there is an fwrite function as well fclose($fileHandle);Here fread reads in its second parameter many bytes.
$line = fgets($fileHandle, $max_num_bytes_line); //this is an fputs function as well
$string = file_get_contents("my.dat"); $string .= "foo"; file_put_contents("my.dat", $string);
$lines = file("my.dat");