PHP Interactive Web Systems
PHP PHP is an open-source server side scripting language. PHP stands for PHP: Hypertext Preprocessor One of the most popular server side languages Second most popular on GitHub (after Python) Supported by basically all non-iis web servers Very active development community Tons of learning resources
About PHP PHP has a syntax very similar to most other languages, including Java, which you should have some familiarity with: if (true) { print "Something!"; }
Using PHP PHP only works with a PHP Processor (generally on a server) Opening a PHP file in a web browser will not give an expected result Browsers don't "know" php Files must be place in a server directory Anywhere in your Cloud 9 workspace SECS Server: login.secs.oakland.edu Directory: ~/public_html
Using PHP PHP files use the.php extension Files without PHP will not have the code processed, and will be sent to the client All output from PHP is "text" in nature PHP does not have a direct user interface Even images are "text" behind the scenes PHP code must be placed within PHP tags <?php and?> Anything not within PHP tags is treated as a literal Meaning it is output directly
PHP Example PHP File: <!doctype html> <html> <title>my PHP</title> <body> <?php echo date('r');?> </body> </html> HTML Output to Client: <!doctype html> <html> <title>my PHP</title> <body> Tue, 10 Feb 2015 12:23:21 </body> </html>
PHP BASICS
Comments in PHP To comment in php, you add //. Anything from there to the end of the line will be commented out echo Hello World"; //Output To comment out an entire block, start with /* and end with */ /* Everything in here is a "comment" print "even code"; */
Variables Used to store values for future use All variables must start with a $ Followed by a _ or letter, then combination of letters, numbers, and underscores Can only contain A-z, 0-9, and _ $myvar - Good $1var - Bad Case sensitive $myvar is not the same as $myvar
Variables PHP variables are loosely typed Their type is not declared, and may change over time Type is based on what you put into the variable Variables are declared implicitly You do not have to explicitly declare the variable, simply putting something into a variable creates it if it does not exist $username = john'; // string $points = 234; // integer $cost = 45.87; // float $response = true; // boolean
PHP Variable Types int, integer float, double, real string bool, boolean array resource NULL object
echo and print echo and print are used to output content such as strings and numbers (which will output as a string). The are basically identical Both may be used with or without () echo "Something"; echo("something"); print "Something"; print("something");
Arithmetic Order of Operations - Standard Parentheses ** (exponent) *, /, % (modulus), in left-to-right order +, -, in left-to-right order Use parentheses!!
Increment / Decrement Shorthand for increasing or decreasing a variable by one $a++ Post-increment $a-- Post-decrement Return $a then increment $a by one Return $a then decrement $a by one ++$a Pre-increment Increment $a by one, then return $a --$a Pre-decrement Decrement $a by one, then return $a $a = 8; echo $a++; 8 echo $a; 9 echo ++$a; 10 echo $a; 10
Concatenation Used to append strings together PHP uses the dot operator (. ) $new = $string1. $string2;
Assignment = assigns a value into a variable Shorthand assignment $a += $b is the same as $a = $a + $b +=, -=, *=, /=, %=,.=, **=
Comparison Operators Comparison operators apply the appropriate comparison to the items to the left and right, and "return" either true or false <, <= >, >= ==, === - Equality!=,!== - Not equality Not '='!
== vs === Two different equality operators == compares equality in value, but not necessarily type Ignores the distinction between: Integers, floating point numbers, and strings containing the same numeric value will return true Non-zero numbers and boolean TRUE Zero and boolean FALSE An Empty string or the string "0" and the boolean FALSE Any other non-empty string and boolean TRUE === compares equality in both value and type
Logical Operators $a && $b Logical And - True if $a and $b are True $a and $b Logical And $a $b Logical Or - True if either $a or $b are True $a or $b Logical Or $a xor $b Logical Xor - True if either $a or $b are True, but not both!$a Logical Not - True is $a is not True The difference between && and and (as well as and or) is that and and or have lower precedence than && and
Logical Operators - Short-circuiting All PHP logical operators skip evaluations if they can" false && never_runs() Never evaluates because && can now never return anything but false true never_runs() Never evaluates because can now never return anything but true
Operator ** Right ++ -- Right! Right * / % Left + -. Left Associativity < <= > >= Non- Associative && Left Left = += -= *= **= / =.= %= and xor or Right Left Left Left ==!= ===!== <> Non- Associative Order of Operations
Order of Operations - Associativity When there are multiple operators of the same precedence, they are grouped based on their associativity: Left: $a + $b + $c is executed as ($a + $b) + $c Right: $a = $b = $c is executed as $a = ($b = $c) Non-Associative This means they cannot be used next to each other 0 < $a < 10 is not allowed in PHP
gettype() gettype() takes a variable and returns the name of the type $foo = "bar"; print gettype($foo); // Prints "string"
settype() settype() allows you to change the type of a variable: $foo = "3.14"; settype($foo, "int"); // $foo is now the integer 3
Converting Variable Types Casting $var = "3"; // String; $var2 = (int)$var; // Integer
STRINGS
Single and Double Quotes Single quotes - $str = 'My String'; Taken (almost) completely literally Does not replace variables or most escape sequences Double quotes - $str = "My String"; Processes string, looking for variable names Replaces standard escape sequences
Single and Double Quotes When a string is started by one type, only the same type can end it echo 'This is a string"; Parse error: syntax error, unexpected ''This is a string";' (T_ENCAPSED_AND_WHITESPACE) in /Users/merrill/test.php on line 3 echo 'This is a "quote"'; This is a "quote"
Escape Sequences Start with a \ - The next characters shows what to do: \n Replace with the newline character \r Replace with the return character \t Replace with a tab \\ Replace with a backslash \' Replace with a, not breaking the string \" Replace with a ", not breaking the string Single quote strings only replace \\ and \'
Escape Sequences print "This is\na new line"; This is a new line print 'This is\na new line'; This is\na new line
Escape Sequences echo "This is a "quote" of someone"; Parse error: syntax error, unexpected 'quote' (T_STRING), expecting ',' or ';' in /Users/merrill/test.php on line 3 echo "This is a \"quote\" of someone"; This is a "quote" of someone
Variable Replacement Searches double quote string for known variable and replaces them $type = "Dog"; print "This is a $type"; This is a Dog
Variable Replacement Use curly braces {} to make it less ambiguous $type = "Dog"; print "There are many $types"; Notice: Undefined variable: types in /Users/merrill/test.php on line 5 There are many $type = "Dog"; print "There are many {$type}s"; There are many Dogs
Aside - PHP Function Names Built in PHP functions do not follow a consistent naming scheme as you will see Frequently have to look up function name Good hinting text editor is very handy
Various String Functions strlen() Returns the number of characters in a string. str_word_count() Returns the number of words in a string. strrev() Returns a reversed version of the string
Various String Functions strpos() Returns the zero indexed position of the search item strpos("this is my string", "my"); //Returns 8 str_replace() Replace all instances of search with replacement in a string str_replace("re", "Dis", "Replace"); // Returns "Displace"
CONTROL STRUCTURES
if if (condition) { // Do something } else if (condition2) { // Do something } else { // Do something }
Ternary Operator PHP has a special conditional operator called the Ternary Operator: (condition)? (result 1) : (result 2) If the condition is true, then the operator evaluates to result 1 if the condition is false. then the operator evaluates to result 2 Very hard to read. I recommend against using it in general.
Ternary Operator $a = 6; echo $a > 5? "$a is >5" : "$a is <=5"; 6 is >5 A special note - the ternary operator is an expression which evaluates to a value, not a variable, this means: The results must be representable as a number or string If you assign the result of the expression into a variable, that variable will hold a copy of the value, not a reference to the selected variable
switch switch ($var) { case 1: // Do something break; case "b": // Do something break; default: // Do something }
Loops while: while (expression) { // Do something } for: for ($i = 0; $i < 10; $i++) { // Do something } do...while do { // Do something } while (expression);
ARRAYS
Aside - print_r() Used to output a variable in a human readable format, regardless of content. Mainly used for debugging $arr = array(); $arr[] = "0"; $arr[] = 0; $arr[] = false; $arr[] = null; print_r($arr); Array ( [0] => 0 [1] => 0 [2] => [3] => )
Aside - var_dump() Very similar to print_r(), but also includes information about the type and size of information within each variable $arr = array(); $arr[] = "0"; $arr[] = 0; $arr[] = false; $arr[] = null; var_dump($arr); array(4) { [0]=> string(1) "0" [1]=> int(0) [2]=> bool(false) [3]=> NULL }
Arrays Used to store many values Unlike Java, their size is not fixed, you can add and remove elements at any time Elements may be addressed by an integer or by string When a key is a number, it is an index When a key is a string, it is a name An array may have both index keys and name keys An array with key names is generally known as an Associative Array
Arrays - Creation All are valid: $arr1 = array(); $arr2 = array("val1", "val2", "val3"); $arr3 = array("key1" => "val1", $arr4[] = "val1"; "key2" => "val2"); $arr5 = ["val1", "val2", "val3"]; $arr6 = ["key1" => "val1", "key2" => "val2"];
Arrays - Appending Just assigning to $array[] will add the value to the end of the array, giving it a index one larger than the largest previously used number: $arr = array(); $arr[] = "val1"; $arr[5] = "val2"; $arr[] = "val3"; print_r($arr); Array ( [0] => val1 [5] => val2 [6] => val3 )
Arrays - Associative Use a string key instead of a index number: $arr = array(); $arr["key1"] = "val1"; $arr["key2"] = "val2"; print_r($arr); Array ( [key1] => val1 [key2] => val2 )
Arrays - foreach Loops through all the elements in an array: foreach ($arr as $element) { // Do something } Or foreach ($arr as $key => $element) { // Do something }
Arrays - Sorting sort() Sort array in ascending order rsort() Sort array in descending order asort() Sort associative array in ascending order by value ksort() Sort associative array in ascending order by key arsort() Sort associative array in descending order by value krsort() Sort associative array in descending order by key
Arrays - Sorting They sort "in place": $arr = array(5, 1, 2,6); sort($arr); print_r($arr); Array ( 0 => 1 1 => 2 2 => 5 3 => 6 )
FUNCTIONS
Functions Defined much like most other languages: function myfunction1() { // Do something } Name can start with an underscore or a letter (not a number Unlike variable names, function names are not case sensitive
Arguments When functions are defined with arguments (also known as parameters), those variables will exist in the function, with the values passed: function myfunction($param1, $param2) { echo $param1; echo $param2; } myfunction("one", "Two"); Arguments are pass OneTwo
Arguments Arguments are passed in the calling order, and have nothing to do with the names given: $var1 = "A"; $var2 = "B"; myfunction($var2, $var1); "B" "A" function myfunction($var1, $var2) { echo $var1; echo $var2; BA }
Default Argument Values You can define what will be used if the argument is not supplied: function myfunction($param1 = "One") { echo $param1; } myfunction(); One
Default Argument Values If a default is not defined, the argument is required! function myfunction($param1) { echo $param1; } myfunction(); Warning: Missing argument 1 for myfunction(), called in /Users/merrill/test.php on line 6 and defined in /Users/merrill/test.php on line 3
return Terminates the current function are "returns" control back to the calling function. If followed by a value, that value is returned to the location the function was called function myfunction() { return "Bob"; } print "My name is ". myfunction(); My name is Bob