CS174
Chris Pollett
Sep 22, 2010
$arr=array(1,2,3); echo $arr[2]; /* would print 3 */
$carr = array(); //creates an empty array
$arr = array( 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.
$cities = array("San Jose", "San Diego"); echo current($cities); // prints San Jose $another = next($cities); // $another is now San Diego;
$lows = array("Mon" => 23, "Tue" => 18); foreach($lows as $day =>$temp ) {echo "$day lows were $temp";}
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).
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("/:/", "apples:oranges"); //would act like Perl's split //preg_match acts like acts like Javascript match.
<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>
$fileHandle = fopen("my.dat", "r"); $file_string = fread($fileHandle, filesize("my.dat")); fclose($fileHandle);Here fread reads in its second parameter many bytes.
$line = fgets($fileHandle, $max_num_bytes_line);
$string = file_get_contents("my.dat");
$lines = file("my.dat");
$fileHandle = fopen("my.dat", "w"); // use "a" for append fwrite($fileHandle, $out_data); fclose($fileHandle);
file_put_contents("out.dat", $str);
$fp = fopen("/tmp/lock.txt", "w"); if (flock($fp, LOCK_EX)) { // do an exclusive/write lock. use LOCK_SH (for shared/read lock) fwrite($fp, "Write something here\n"); flock($fp, LOCK_UN); // release the lock } else {echo "Couldn't lock the file !";} fclose($fp);Locks are released when fclose() is called.