PHP Basics



About

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.

Server Side Programming

PHP, and other server side languages, works differently from JavaScript. PHP is processed on the server and the results of the scripts are sent to the user's browser. This enables variables to be checked without the threat of the user seeing the conditions (unlike JS which can be seen using View Code).

This does present some unique challenges in that PHP cannot directly interact with JavaScript on a given page because by the time the JS is running, the PHP has finished. However, we can use PHP to generate JS, HTML and CSS.

This concept of code running on the server also means that PHP does not have an input method. Again, by the time the user would be able to enter information in a form (HTML), the PHP would have already finished running.

The benefit to server side scripting is that we can pass information from page to page as the values are passed from the page, to the server, and can then be sent back out the page. This is most often seen in the processing of forms.

Output with PHP and HTML

PHP, as previously stated, runs on the server and sends its output to the client. Most often, the output of PHP is HTML, CSS and JavaScript. There are a variety of ways to mix your PHP code and HTML code to achieve your desired output.

HTML in PHP
This is the method that many beginning PHP programmers take. It is functional, but requires the programmer to keep track of a lot of quotes and to manage a lot of concatenation.
echo "<section class='main'>"
echo "<h1>Section 1</h1>"
echo "<hr/>"
$ name="Bob"
echo "Welcome, ".$ name
echo "Text Text Text."
echo "</section>"
PHP in HTML
This is a more elegant solution to the problem. In this version (of the same output), the programmers main language is HTML, and PHP is written only where needed.
< ?php $name="Bob"; ? >
<section class='main'>
<h1>Section 1</h1>
<hr/>
Welcome, < ?php echo $ name; ? >
Text Text Text.
</section>
In the above examples, note that there are sometimes spaces in the php langauge declarations and variable declarations. This is for display only to avoid the server mistaking the display code for actual code it should run.

PHP Basics (for programmers)

PHP is typically not a starting language for programmers as the concept of server side programming is advanced. So, the chart below assumes prior programming knowledge (specifically in Java and/or JavaScript) and shows some of the basics of the language including output, arrays, control structures, and methods.

JavaJavaScriptPHP
Script Tags N/A <script>...</script> <?php ... ?>
Variables int x=0; var x=0; $x=0;
Concatenation "Hello, "+name; "Hello, "+name; "Hello, ".$name; OR "Hello, $name";
Output System.out.print("hello"); document.write("hello"); echo "hello";
if...else if(condition)
&tab;code
else
&tab;code
if(condition)
&tab;code
else
&tab;code
if(condition)
&tab;code
else
&tab;code
for loop for(int x=0; x<5; x++) for(var x=0; x<5; x++) for($x=0; $x<5; $x++)
while while(x<5) while(x<5) while($x<5)
Comments //single line
/* block */
//single line
/* block */
//single line
/* block */
Processing Compiled Client Side Server Side
Casting Integer.parseInt(myAge) parseInt(myAge) (int)$myAge
Arrays double [] arr=new double[3];
double [] arr={1,2,3};
arr[x];
arr.length;
*fixed size
var arr=[];
var arr={1,2,3};
arr[x];
arr.length;
*dynamic sizing
$arr=array();
$arr=array(1,2,3,4,5);
$arr[$x];
count($arr);
*dynamic sizing
Methods function(parameter){
code;
return;
}
function(parameter){
code;
return;
}
fuction($parameter){
code;
return;
}
Overloading allowed not alllowed not allowed


Math, String and Array Methods

In many languages, like Java and JavaScript, Math methods are called from the Math class and String and Array methods are typically called from objects of those classes. PHP operates differently, where all of these methods are NOT called from objects or classes, but instead take those objects as parameters. Below are some standard conversions between JavaScript and PHP standard methods.
JavaScriptPHP
Rounding Math.ceil(x)
Math.floor(x)
Math.round(x)
ceil($x)
floor($x)
round($x)
Comparisons Math.min(n1, n2, n3...)
Math.max(n1, n2, n3...)
min($x, $y)
max($x, $y)
Powers Math.pow(base, exp)
Math.sqrt(num)
pow($base, $exp)
sqrt($num)
Pi Math.PI pi()
Case Conversions str.toUpperCase()
str.toLowerCase()
strtoupper($str)
strtolower($str)
String Length str.length strlen($str)
Substrings str.substring(start, end) substr($str, $start, $end)
trim($str)
Array Methods arr.pop()
arr.push()
arr.splice()
array_pop($arr)
array_push($arr)
sort($arr)
Random Numbers
In order to generate random numbers in PHP, we need to set the seed. Often, we set this from the clock. To set the random seed, use the srand() function.
srand((double)microtime()*1000000);
Once the seed has been set, we can call the rand() method that takes two parameters, a min and a max.
rand($min, $max);
The benefit to setting the seed is that if we were to set the seed to a number other than the clock (which is always changing), we would get the same set of "random" numbers each time we ran the program, which is great for testing and debugging.
srand(5);
echo rand(1, 10).", ";  //2
echo rand(1, 10).", ";  //5
echo rand(1, 10);       //8

String to HTML Conversions
Often, in PHP, we find ourselves nesting quotes inside of quotes (at least more often than we may have in Java or JavaScript). This will happen with more frequency when PHP is integrating with a database (e.g. MySQL) or taking user input from a form. Programmers then find themselves displaying and/or storing escape sequences, including the slash. The fix to this is found in two methods: The names are fairly self-explanatory. addslashes will take the string parameter and add slashes in front of required characters (e.g. single quotes and double quotes). stripslashes, on the other hand, removes the slashes.
$str="Then she said, \"Hello\"!";

echo $str;				  
//Then she said, "Hello"!
	
echo stripslashes($str);  
//Then she said, "Hello"!
	
echo addslashes($str);    
//Then she said, \"Hello\"!
	
$strWithSlashes=addslashes($str);
echo $strWithSlashes.;    
//Then she said, \"Hello\"!
	
echo stripslashes($strWithSlashes);
//Then she said, "Hello"!

Another timesaving method for strings when dealing with PHP and HTML is the nl2br($str) method. nl2br stands for NewLine To LineBreak. The purpose of this method is to take an enter character (from a DB or user input form) and convert the enter (or newline \n) character to a <br/> for use in HTML.
$str="Line 1\nLine2";
echo $str;
//Line1 Line2

echo nl2br($str);
//Line1
//Line2

Associative Arrays and Sorting
PHP provides a type of array called an associative array. In an associative array, array values can be accessed using a string, called a key, instead of a number. This type of array is not avaiable in Java or JavaScript. Here is an example of an associative array:
$arr=array("first"->"Clyde");
echo $arr['first'];
In line(1), an array is created and an element is pushed into the array. The value "Clyde" is stored in an array cell that can be accessed by the key "first".
Line (2) then accesses and outputs the value ("Clyde") that is associated with the key ("first").
Associative arrays are traversed using a foreach loop as follows:
foreach($arr as $key->$value){
	-code-
}

PHP also provides some methods to simplify the sorting of arrays. In each case, the array is sent as a parameter and the result is returned:

PHP Dates

PHP has access to the server clock. This allows it to access the current date and time. Additionally, you can create a date/time value to be formatted. The date function takes a string parameter that is the format of the date you desired to display. The optional second parameter of the date function specifies the date to be formatted. Without the optional second parameter, PHP will format the display the current date/time. Below, you will find some common date formatting characters. For a complete list, check the php date method page.
echo date("F j, Y");
//uses the current clock
//November 21, 2024

echo date("F j, Y", strtotime("11:59pm December 31, 1999"));
//uses the strtotime function 
//which takes a times as a string
//December 31, 1999

echo  date("F j, Y", mktime(12, 0, 0, 1, 1, 2000));
//uses the mktime function
//hours, minutes, seconds, month, day, year
//January 1, 2000

Variable Scope in PHP