PHP was created in 1995 by Rasmus Lerdorf to keep track of his Personal Home Page. It was updated in 1997 by Andi Gutmans and Zeev Suraski as a total rewrite of the original, now aimed towards e-commerce applications. The new version of PHP stands for PHP Hypertext Preprocessor. PHP is an open-source document, so it is constantly being updated and improved. It is a slight transition from JavaScript as PHP is server side scripting, but most of the previously learned programming constructs are the same.
JavaScript to PHP
| JavaScript | PHP |
Script Tags |
<script>...</script> |
<?php ... ?> |
Variables |
var x=0; |
$x=0; |
Concatenation |
"Hello, "+name; |
"Hello, ".$name; OR "Hello, $name"; |
Output |
document.write("hello"); |
echo "hello"; |
if...else |
if(condition) &tab;code else &tab;code |
no change |
for loop |
for(var x=0; x<5; x++) |
for($x=0; $x<5; $x++) |
while |
while(x<5) |
while($x<5) |
String length |
myString.length() |
strlen($myString) |
Comments |
//single line /* block */ |
no change |
Processing |
Client Side |
Server Side |
Casting |
parseInt(myAge) |
(int)$myAge |
Random Numbers |
parseInt(Math.radom()*(high-low)+low); |
srand((double)microtime()*1000000; rand(min, max); |
Arrays |
shift(), unhift(), pop(), push(), splice() |
array_shift(), array_unshift(), array_pop(), array_push() |
Methods |
function(parameter){ code; return;} |
no change |
Helpful Hints
- Since PHP is server side, it is interpreted before any informatin is sent to the browser. thus, it is possible to embed PHP commands directly in HTML code. Remember to include any PHP code in the <?php ... ?> script delimeters.
- PHP code must be run from the servers, so if you page is not working make sure that the server is running and that the page is saved as php.
- To echo HTML or JavaScript code that requires double quotes, you must escape the double quotes. echo ""
- Adding newline charactes in your PHP echo statements will make the resulting code more readable
- You may consider appending type abbreviations on variable names to help discern the stored information. Ex: $nameStr, $priceDbl
- No matter how many random numbers you want to generate, you should only call srand once per script.
Working with Arrays
- PHP allows for both index based and associative arrays
- To create an index based array: $arr=array(); to create an empty array or $arr=array("one", "two","three") to auto fill with predetermined values. Index based array values are accessed using an integer index $arr[1]="hello";
- Associative arrays use keywords as the indices. The keywords must be unique to the array - in other words one array cannot have the same keyword twice. To create an associative array, use $arr=array('first'->'Mickey', 'last'->'Engel'); Accessing the values is as follows echo $arr['first'];
- Multidimensional arrays are created by making an array as an element of another array.
- Array size can be found using count($arr);
- Associative arrays can be traversed using foreach($arr as $key->$value) {code}
- PHP includes methods for sorting arrays:
- sort($arr) - sorts an index based array by value
- asort($arr) - sorts an associative array by value
- ksort($arr) - sorts an associative array by key
- shuffle($arr) - randomizes the order of elements in an array
- array_reverse($arr) - returns an array in reverse order of the way it went in
The Math Class
Unlike JavaScript, the use of the Math class name in front is not necessary.
- ceil($num) - rounds up
- floor($num) - rounds down
- max($n1, $n2) - returns bigger number
- min($n1, $n2) - returns smallest number
- pi() or M_PI - value of pi
- pow($b,$e) - raises b to the e power
- rand($min, $max) - generates a random integer between min and mx
- round ($num) - rounds the number
- sqrt($num) - square root
- srand$(opt) - seeds random number generator, opt is an optional seed value
Working with Strings
Unlike JavaScript, string method are not called from objects, but as class methods and take string variables as parameters
- addslashes($str) - returns a string with slashes before characters that need to be escaped
- explode($delim, $str) - returns an array of strings from $str separated by $delim
- implode($glue, $pieces) - creates a string of elements from an array $pieces separated by $glue
- md5($str) - returns an encrypted version of the string
- nl2br($str) - inserts html breaks before all newlines in a string
- stripslashes($str) - un-escapes any escape characters
- strlen($str) - the length of a string
- strtoupper($str) - returns uppercase version of a string
- strtolower($str) - returns the lowercase version of a string
- substr($str, $start, $length) - returns a substring of str starting at $start of $length
- trim($str) - trims whitespace from beginning and end of string
Dates
PHP can access the server clock to determine the date and time.
The first step is to call the date() method that takes a string $format and returns a formatted date/time. There is an optional second parameter that allows the caller to choose the time to be formatted. Lack of that parameter will format the current time.
- The $format string uses the following characters:
- D - a textual representation of a day with three letters
- j - the day of the month without leading zeros
- l - a full text representation of the day of the week
- S - the english ordinal suffix for the day of the month in 2 characters
- F - full text representation of the month
- n - numeric representation of the month without leading zeros
- t - the number of days in the given month
- Y - a 4 digit representation of the year
- a - lowercase ante meridian and post meridian
- g - 12 hour format of an hour without leading zeros
- i - minutes with leading zeros
- s - seconds with leading zeros