Science Library - free educational site

PHP basics

PHP is a common computing programme. It is an alternative to ASP.NET, JSP, ColdFusion, and Ruby on Rails.

PHP was invented by Rasmus Lerdorf in 1994. It was originally conceived as a simple programme to track the visitors to his online biography, so he gave it the innocuous and now totally inappropriate name of 'Personal Home Page'!

Rasmus Lerdorf
Rasmus Lerdorf, Greenlandic computer programmer, inventor of PHP

As it was adapted to a far greater range of applications, it was renamed 'PHP: Hypertext PreProcessor' (ok, not perfect as acronyms go, but close enough!).

PHP is defined by the PHP website (www.php.net) as: "a widely used general-purpose scripting language that is especially suited for Web development and can be embedded into HTML."

PHP is a server-side scripting language. This means that PHP is inserted within an HTML page, but acts on the server. To use PHP, it is necessary to have access to a server, which may be a remote computer, which is the internet access gateway, or a local server on the same computer, using a server application like Apache.

PHP file extension

If a file contains any PHP, it needs to have the extension .php

For example, your first PHP file could be called: myfirstphpfile.php, and would be placed wherever you need it on the site.

PHP code that is used by more than one page could be placed in a separate file and folder, and included in the HTML script when needed.

PHP Tags

PHP is embedded within an HTML file. Special tags are used to identify the PHP script. These are:

<?php

...

?>>/p>

PHP Comments

PHP has three ways of including comments: two for a single line, and one for a comment that stretches over multiple lines:

# Comment which does not get displayed

// Comment which does not get displayed

/* Comment which does
not get displayed
and wants to take its time about it */

PHP statements

PHP uses statements which must conclude with a semi-colon (;):

<?php

/* Example of a PHP statement for printing out
a phrase on the displayed page*/

echo 'This is printed on the page';

echo "This is printed on the page";

print 'This is another way to print text to a page';

print "This is another way to print text to a page";

/* HTML tags may be included in an echo or print statement
provided they appear within the quote marks*/

echo '<p>This is printed on the page</p>';

?>

PHP Variables

Variables are exactly as their name suggests: variable. If a quantity is not a variable (cannot - or should not - change), then it is a constant (always the same).

To define a constant:

define('LANG', 'english');
echo LANG; //Note: the definition requires quotes, but the use does not

To define a variable in PHP, use a dollar sign ($). e.g. the variable which is the name of a customer being called from a database of many hundreds of customers could be defined as: $name

Concatenation

Variables can be defined (or redefined) at any point in a script. They can also be added together: for example, the full name of a customer could take the two parts of the name and combine them: $fullname = $firstname.$lastname

A problem with this example is that the two name parts will have no space between them. The following example demonstrates how concatenation may be used to include non-variable elements, such as a space or a line break (<br />), into a variable:

<?php

$firstname = 'Fred';

$lastname = 'McGurty';

$fullname = $firstname.$lastname;

echo $fullname;

$fullname = $firstname.' '.$lastname;

echo $fullname;

$fullname = $lastname.', '.$firstname;

echo $fullname;

?>

The output of this code is FredMcGurty, Fred McGurty, and McGurty, Fred

Variable names

Variables are case sensitive and can include the underscore. These variable names: $Customer, $customer and $_customer, are all valid and refer to different stored values.

Variable names may include numbers, but the first character after the dollar sign ($) must be a letter or an underscore (_). $variable1 and $_variable1 are valid, but $1variable is not.

For clarity, a common technique to make variable names with multiple words more readible is to use the 'camelCase'. Instead of making a variable for 'my next great idea' $mynextgreatidea, we use the camel case to make it more legible: $myNextGreatIdea

Assignment Operator =

The equals sign (=) is used to assign a value to a variable. If the variable does not exist, the assignment also creates a new variable with this name. If the variable exists and has a previous value, the assignment replaces the previous value with the new value in the assignment statement. For example:

<?php

$newVariable = '42';

echo $newVariable;

?>

The output will be 42

<?php

$oldVariable = '42';

$oldVariable = '21';

$newVariable = $oldVariable;


?>

The $oldVariable value (42) is replaced by the new value (21). In this example, a new variable is then created and given the same value as the old variable.

Now, examine the difference between these two echo statements:

<?php

echo 'The value stored in the newly created variable $newVariable is '.$newVariable;

echo "The value stored in the newly created variable $newVariable is ".$newVariable;


?>

The outputs are:
The value stored in the newly created variable $newVariable is 21

and: The value stored in the newly created variable 21 is 21

Notice that when the variable name is inside single quote marks (' ') in the echo statement, the script prints out the string literally, even though it is a variable name. Everything inside the quote marks of an echo statement is considered a string.

If, instead, double quote marks (" ") are used in the echo statement, the variable name is interpreted as a variable and its value printed out instead of the string.

Best Practice

Single quote marks will print literally what you write.

Use double quote marks if you want to print the value of the variable instead.

Variable Types

Variables can be different types. Specifying the type can enable the programme to carry out certain operations. The two main types are string and number.

Strings

A string is simply a series of alphanumeric characters in a sequence. These characters can be letters, numbers, punctuation symbols (except the period (.), which means concatenate) and spaces.

To store the string as the value of a variable, simply define the variable as that string, using quote marks (single or double):

<?php

$Variable = 'This is a string: 42 is my favourite number!';

$Date = "18 August, 1996";

$Number_YearsInCentury = '100';


?>

The backslash character may be used to inform the programme that next character is to be used as a string character, and not an operator. For example, if a string is within single quotes, but it is desired to insert a string with a single quote as an apostrophe, it is necessary to 'escape' the quote with a backslash:

<?php

$newVariable = 'My friend's dog is called Fido';

?>

This will result in the string 'My friend' being stored in the variable $newVariable

To prevent this truncation, the apostrophe is escaped:

<?php

$newVariable = 'My friend\'s dog is called Fido';

?>

Numbers

Variables may also be numbers, permitting calculations to be made dynamically and inserted into a page text or form.

<?php

$price = 100; //price in euro

$discount = 10; // discount rate in percentage

$salesprice = $price - $price*($discount/100);

$quantity = 20; // number of items bought

echo 'Good morning, you have made a purchase of '.$quantity.' items at €'.$price.' each.
After a special offer of '.$discount.'%, you pay a total of €'.$salesprice*$quantity.'.
Thankyou for your custom.';


?>

Constants

Constants are named elements which do not change value in a particular script.

They are defined as follows:

<?php

define ('PHP', '5.5.15');

echo 'The latest version of PHP available is '. PHP;

?>

String Operations

String Operations (PHP) can carry out a number of useful operations on strings:

ucwords(): converts the first character of all words to Uppercase

strtoupper(): converts all characters to UPPERCASE

strtolower(): converts all characters to lowercase

str_replace("Zaphod","Arthur","Hello Zaphod!"): replaces 'Zaphod' by 'Arthur' in the string "Hello Zaphod!"

str_word_count("Hello Arthur!"); // outputs 2

strpos("Hello Arthur!", " "); // outputs 5 (i.e. finds the space)

trim(); // removes white space from both ends of string

chop(); // removes white space from end of string

$str = "Hello Arthur!"; echo chunk_split($str,1,"."); // outputs 'H.e.l.l.o. .A.r.t.h.u.r.!.'

strtok($string, " "); // splits a string into words separated by a space

Content © Renewable-Media.com. All rights reserved. Created : August 10, 2014 Last updated :February 14, 2016

Latest Item on Science Library:

The most recent article is:

Trigonometry

View this item in the topic:

Vectors and Trigonometry

and many more articles in the subject:

Subject of the Week

Universe

'Universe' on ScienceLibrary.info covers astronomy, cosmology, and space exploration. Learn Science with ScienceLibrary.info.

Science

Great Scientists

Adam Smith

1723 - 1790

Adam Smith was a Scottish economist, or indeed 'the Father of Modern Economy'. He penned the Wealth of Nations, published in 1776, a not insignificant year for revolutionary ideas...

Read about history on ScienceLibrary.info
Umwelt.Science

Quote of the day...

Capitalism is the astounding belief that the wickedest of men will do the wickedest of things for the general good of everyone.

ZumGuy Internet Promotions

Renewable energy media services