Xah Lee, 2009-01-26
PHP code must be enclosed between markers like this <?php … ?>. Anything outside of it is printed as is.
<?php # this is comment. (bash style) // comment too, start with 2 slashes. (C style) 5 + 4; /* Java, C++ style comment is also supported. */ ?> hi mom
Save the above as “myfile.php”. You can run it in the command line like this: “php myfile.php”, or, you can run it in browser thru http server. The result output is: “hi mom”.
<?php $x = 5; # single quoted string's contents are literal # the \n will be printed as blackslash and n echo 'hi sweetie\n'; # double quoted strings are interpreted. # including chars like \n, and variable become values echo "i have $x apples \n"; # string can contain unicode chars, or literal line break echo "α β λ ≤ ≥ ≠ ⊂ ℚ ℝ ℂ ∑ ↔ ⇔ ◀▶▲▼\n"; # string join echo "Once" . " upon a time"; ?>
If you are printing Unicode, your html should declare unicode encoding. See: Character Sets and Encoding in HTML.
<?php # substring, use substr( $myStr, $startIndex, $length)”. Index starts with 0 $a = "once upon a time"; echo substr($a,0,4); // prints “once” ?>
<?php # string length $a = "once"; echo strlen($a); // prints 4 ?>
“true” and “false” are built-in boolean type. Case does not matter.
When a value is used in a true/false context, such as in “if” statement, the following values are considered FALSE:
<?php $x = 4; $y = 5; if ($x <= $y) {echo "yay!";} if ($x == $y) {echo "yay!";} else {echo "Nay!";} ?>
<?php $a=3; $b=4; if ($a > $b) { echo "O No!"; } elseif ($a == $b) { echo "O Yes"; } else { echo "Problem!"; } ?>
<?php $i = 1; while ($i < 9) { echo "woot!"; $i++; } ?>
<?php for ($i = 1; $i < 9; $i++) { echo $i; } ?>
Keyword “break” can be used to exit a loop. Example:
<?php for ($i = 1; $i < 9; $i++) { echo $i; if ($i == 5) {break;} } ?>
Variables do not need to be declared. All variables must have a dollar sign “$” in front. ( A variable always just have a dollar sign in front, regardless what value it holds. Unlike perl, the “sigil” does not change depending on the value of the variable. In PHP, there's no perl's concept of “context”.)
Basically all variables are global. Variables inside functions definition are local to that function. To refer to global vars inside function definition, use “global” in front of the var.
Using a curly brace block “{…}” does NOT make variables inside it local.
PHP combines the concepts of “array/list” and “hash/keyed-list” into one, just called array.
A PHP array is just a sequence of things. Each element is actually a pair, made of a “key” and a “value”. The “key” can be omitted if you don't need a list of pairs. If a key is omitted, they are automatically generated using incremental indexes starting from 0.
Here are examples of manipulating array as simple list without using the “key”. For using array as a keyed-list (aka hash-table, dictionary, associative list), see keyed list.
Array is constructed using this form “array()”. Here's a simple example:
<?php $x = array(7,2,3,"yes",5); print_r($x); ?>
Use “count()” function to get the number of elements.
<?php $x = array(7,"yes",5); echo count($x); // prints 3 ?>
Extracting element can be done by this form “$arr[key]”.
<?php $x = array(7,2,3,"yes",5); echo $x[1]; // prints 2 ?>
<?php $x = array(7,"yes",5); $x[1] = "no"; echo $x[1]; // prints no ?>
Adding a element is done by the form “$arr[newKey]=val”. The “newKey” must be a key that does not exist already, otherwise it simply replace that key's value.
If you are using array as simple list “without keys”, and have never removed any element in your list, you can add new ones with automatic index like this: “$myList[]=newVal”.
<?php $x = array("nil", "bi", "tri"); $x[]="quad"; print_r($x); ?>
To delete a element, use “unset()”.
<?php $x = array(7,"yes",5); unset($x[1]); // removes the "yes" print_r($x); // element with index 1 no longer exist. ?>
WARNING: Once a element is deleted, there no longer exist a element with that element's index. In other words, the array is not “re-indexed”, and in fact there is no such concept as “re-indexing”. If you want the index to be sequential starting from 0 again, just create a copy like this: “$newA = array_values($oldA);”.
Arrays can be nested arbitrarily.
<?php $x = array(7,"yes",5); $y = array("woot", $x, "wee"); print_r($y); ?>
To get a element from a nested array, use the form “$arr[key1][key2][…]…”. Example:
<?php $x = array(7,"yes",5); $y = array("woot", $x, "wee"); echo $y[1][0]; // prints 7 ?>
A keyed list (aka hash-table, dictionary, associative list) in PHP is simply called array. It is constructed using the form “array(key1 => val1, key2 => val2, …)”. Example:
<?php $x = array("mary" => 19, "jane" => 16); print_r($x); ?>
To get value of a element, use the form “$arr[key]”.
<?php $x = array("mary" => 19, "jane" => 16); echo($x["mary"]); ?>
Note that the key should be quoted.
To add a entry, use the form “$arr[key] = val”. If the key exist, old value will be replaced. Otherwise, a new entry will be added
<?php $x = array("mary" => 19, "jane" => 16); $x["mary"]=18; // modify a entry $x["vicky"]=21; // add a entry print_r($x); ?>
To delete a entry, use “unset()”.
<?php $x = array("mary" => 19, "jane" => 16); unset($x["mary"]); print_r($x); ?>
To check if a key exists, use “array_key_exists”.
<?php $x = array("mary" => 19, "jane" => 19); echo array_key_exists("mary",$x); ?>
To get just the keys, use “array_keys()”.
<?php $x = array("mary" => 19, "jane" => 16); print_r(array_keys($x)); // (0 => mary, 1 => jane) ?>
To get just the values, use “array_values()”. The function “array_values()” effectively replaces all the keys by numerical indexes starting from 0.
<?php $x = array("mary" => 19, "jane" => 16); print_r(array_values($x)); ?>
To go thru a list, use “foreach”. Here's a example of looping thru a list and accessing its values:
<?php $aa = array("nil","bi","tri"); foreach ($aa as $x) { echo "$x "; } # prints nil bi tri ?>
Here's a example of looping thru a list and accessing both keys and values:
<?php $aa = array("nil","bi","tri"); foreach ($aa as $k => $v) { echo "$k,$v; "; } # prints 0,nil; 1,bi; 2,tri; ?>
Map a function to a array.
<?php function ff($n) {return($n+1);} $a = array(3,9,4); $b = array_map(ff, $a); # $b is (4,10,5) print_r($b); ?>
A function is defined using keyword “function”. Like this:
<?php /* ff($x,$y) returns x + y */ function ff($x,$y) { return($x+$y); } echo ff(3,4); // prints 7 ?>
<?php /* ff($x,$y) returns x + y. If $y is not given, default to 1. */ function ff($x,$y=1) { return($x+$y); } echo ff(3); // prints 4 ?>
A collection of functions can be written and saved into a file. This file can then be loaded using “require()”.
For example, save the following in a file and name it “myPackage.php”.
<?php function ff($x) { return($x+1); } ?>
Now, eval the following code:
<?php require("myPackage.php"); echo ff(3); # prints 4 ?>
“require()” works as if the whole file's content is inserted in-place.
As of PHP 5.2.4 (2007-08), there is no namespace mechanism for importing functions or packages.
blog comments powered by Disqus