PHP is a widely-used general-purpose scripting language that is especially suited for Web development and can be embedded into HTML.
This means PHP can be used to generate HTML. This allows us to adhere to the DRY (Don’t Repeat Yourself
) principle.
A PHP-script is identified by its .php extension and the PHP-tags in the file.
PHP interprets only the code enclosed within the special PHP-tags.
<?php?>Notice that the code outside of the PHP-tags is not interpreted and is printed out unchanged.
A valid PHP instruction generally has the form:
Each statement must be terminated by a semicolon (;)!
An exception to this rule are loops and conditionals. These can encapsulate a block of code in curly brackets {} and thus end in a }…
PHP will ignore everything behind a # or //.
PHP will ignore everything enclosed by /* and */.
To get acquainted with php we will start of on the command line and work our way up to PHP as a web server.
PHP at its core is a program which reads a source file, interprets the directives and prints out the result.
Basic invocation:
The above command will print the output to the STDOUT.
The obligatory hello world.
Create a file: hello-world.php with content:
sudo dnf install php
Run it via:
on the command line.
Variables are a way to store some information and give the storage space a name. Via this name, the content that was stored can be retrieved.
A variable is identified by the leading dollar$-symbol followed by a alpha-numeric sequence.
Warning: It is not allowed to start variable name with a number:
$abc |
OK |
$abc123 |
OK |
$123abc |
Not allowed |
PHP knows two main types of variables:
A scalar variable can hold an atomic quantity. For example: one string, or one number, …
PHP knows four scalar types:
| Type | Example | Description |
|---|---|---|
| Integers | 42 |
Whole numbers |
| Floats | 3.1415 |
Real numbers |
| Strings | 'Hello world' |
Strings can be any number or letter in a sequence (enclosed by single ' or double " quotes, otherwise php may interpret it as a directive…) |
| Boolean | true or false |
binary true or false |
Assign a value to a variable:
Generic syntax:
Examples:
A scalar can be printed via two methods:
Generic syntax:
Echo outputs the provided scalars.
Multiple scalars can be printed at once, just separate them by a comma ,.
Example:
Generic syntax:
Print can only output one scalar at the time. (This can be circumvented via concatenation…)
Example:
Scalars can be combined, concatenated into larger strings.
The concatenation symbol is a dot: ..
You may have already noticed that printing variables enclosed by single quotes ' doesn’t work. The literal variable name is printed instead.
To instruct PHP to interpret the variables, and other special sequences, the string must be enclosed by double quotes: ".
The following special character sequences are interpreted by PHP and formatted accordingly…
| Sequence | Result |
|---|---|
\n |
New line |
\r |
New line (Windows) |
\t |
The literal |
\$ |
Literal $ (escaping prevents variable interpreation) |
\" |
Literal " (escaping prevents string termination). |
Example:
<?php
$variable = "hello world";
echo "1. The value of the variable is: $variable.";
echo "2. The value of the variable is: $variable.\n";
echo "\t3. The value of the variable is: $variable.\n";
echo "4. The value of the variable is: \$variable.\n";
echo "5. The value of the variable is: \"$variable\".\n";Floats an Integers can be used in arithmetic.
| Example | Name | Result |
|---|---|---|
-$a |
Negation | Opposite of $a. |
$a + $b |
Addition | Sum of $a and $b. |
$a - $b |
Subtraction | Difference of $a and $b. |
$a * $b |
Multiplication | Product of $a and $b. |
$a / $b |
Division | Quotient of $a and $b. |
$a % $b |
Modulus | Remainder of $a divided by $b. |
$a ** $b |
Exponentiation | Result of raising $a to the $b ’th power. Introduced in PHP 5.6. |
Example:
Arrays are able to hold more than one item.
An item is stored in the array at a named location. If no name/key/index is explicitly specified, an numeric index from 0 to n (where n is the number of items in the array minus one) is used as the keys.
An array can be declared in two ways:
The []-method can only be used from PHP version 5.4 and higher.
A normal typical array is a list of values. The keys of those values are automatically assigned, starting with zero 0 and auto incrementing for each element added.
See below for how to print and add values to arrays
The keys can however be specified manually:
The function print_r can be used to print an array.
Generic syntax:
A value can be retrieved by specifying the array variable name followed by the index you wish to retrieve enclosed in square brackets:
If the key is a string, the appropriate quoting must be used.
Example:
An array value can be targeted by its key. This key can also be used to update the value:
Example:
Adding an element at the end of an array can be accomplished by the function array_push or by the square brackets notation ($array[] = $value;).
Adding an element in front of an array can be accomplished by the function array_unshift.
Extracting the first element from an array can be accomplished by the function array_shift.
Extracting the last element from an array can be accomplished by the function array_pop.
Counting the elements in an array can be accomplished by the function count.
PHP has some special, reserved, arrays. These arrays are created and filled by PHP.
This array holds all the arguments passed to a PHP-script from the command line.
php print_r-argv.php 'arg1' 'arg2' 123 --optionsArray
(
[0] => print_r-argv.php
[1] => arg1
[2] => arg2
[3] => 123
[4] => --options
)
The $_GET-array holds data sent to a webpage via a HTTP-get method.
This corresponds with URL parameters.
Array
(
[arg1] => hello
[arg2] => world
[end] => !
)
The $_POST-array holds data sent to a webpage via a HTTP-post method.
This is typically done via a from submission…
You can store inter-page data in the $_SESSION reserved array.
This inter-page data is typically:
When files are uploaded, PHP stores information about these files in this array.
Example:
Array
(
[file] => Array
(
[name] => MyFile.jpg
[type] => image/jpeg
[tmp_name] => /tmp/php/php6hst32
[error] => UPLOAD_ERR_OK
[size] => 98174
)
)
It can be very handy to execute a piece of code only when certain requirements are met. This kind of behaviour can be accomplished via conditionals
The if language structure defines the conditions to fulfil and the accompanying block of code to run if the conditions evaluate to true (enclosed in curly brackets {}).
Additionally an else-block can be defined. The code in this block will be executed when the if-condition evaluated to false.
if( /* condition */ ) {
/* execute when condition is true */
}
else {
/* execute when condition is false */
}On top of this, multiple conditions can be chained into an if-elseif-else construct.
if( /* condition 1 */ ) {
/* execute when condition 1 is true */
}
elseif( /* condition 2 */ ) {
/* execute when condition 2 is true */
}
elseif( /* condition 3 */ ) {
/* execute when condition 3 is true */
}
else {
/* execute when conditions 1, 2 and 3 are false */
}Conditionals can also be nested:
if( /* condition 1 */ ) {
if( /* condition 2 */ ) {
/* execute when condition 1 and 2 evaluate to true */
}
else {
/* execute when conditions 1 evalutes to true and condition 2 to false */
}
}
else {
/* execute when condition 1 evaluates to false*/
}| Example | Name | Result |
|---|---|---|
$a == $b |
Equal | true if $a is equal to $b after type juggling. |
$a === $b |
Identical | true if $a is equal to $b, and they are of the same type. |
$a != $b |
Not equal | true if $a is not equal to $b after type juggling. |
$a <> $b |
Not equal | true if $a is not equal to $b after type juggling. |
$a !== $b |
Not identical | true if $a is not equal to $b, or they are not of the same type. |
$a < $b |
Less than | true if $a is strictly less than $b. |
$a > $b |
Greater than | true if $a is strictly greater than $b. |
$a <= $b |
Less than or equal to | true if $a is less than or equal to $b. |
$a >= $b |
Greater than or equal to | true if $a is greater than or equal to $b. |
PHP is a dynamically type language. This means the type of a variable is not set in stone but PHP will try its best to guess the types of variables and convert them (juggle them from one type to the other) where its deemed necessary.
For example:
<?php
$string = '1 as a string';
var_dump($string);
# $string to int = 1 the `+` triggers the type juggling
var_dump( $string + 0);
# -----------------------------------------------------------------------------
var_dump( '1' == 1, 1 == true, 'abc' == true );
var_dump( '1' === 1, 1 === true, 'abc' === true );var_dump prints a variable with type information
Multiple comparisons can be bundled together into one condition. They are combined via the logical operators:
| Example | Name | Result |
|---|---|---|
$a and $b |
And | true if both $a and $b are true. |
$a or $b |
Or | true if either $a or $b is true. |
$a xor $b |
Xor | true if either $a or $b is true, but not both. |
! $a |
Not | true if $a is not true. |
$a && $b |
And | true if both $a and $b are true. |
$a || $b |
Or | true if either $a or $b is true. |
Example:
<?php
if( true or false ) {
echo "`true or false` evaluated to TRUE\n";
}
else {
echo "`true or false` evaluated to FALSE\n";
}
echo "----------------------------------------------------------------------\n";
if( !true ) {
echo "`!true` evaluated to TRUE\n";
}
else {
echo "`!true` evaluated to FALSE\n";
}
echo "----------------------------------------------------------------------\n";
if( true and false ) {
echo "`true and false` evaluated to TRUE\n";
}
else {
echo "`true and false` evaluated to FALSE\n";
}
?>These logical operators can be combined at will. Brackets () can be used to enforce precedence.
Loops enable you to repeat a block of code until a condition is met.
This construct will repeat until the defined condition evaluates to false:
Ctrl+c on the command line to abort the running script.
Danger: The never ending loop:
Info: The pattern $variable = $variable + 1 is used a lot in programming. Therefore shorthand versions of this, and similar operations, are available:
Only while loops are allowed.
For is similar to while in functionality. It also loops until a certain condition evaluates to false. The main difference is the boilerplate required to construct the loop.
The for-construct forces you to define the counter variable and the increments right in the construct.
Notice the semi-colons ; between each of the for-parts!
Only for loops are allowed.
The for construct can also be used to loop over all elements in an array:
$index: $valueThe for and the while construct have their limitations regarding arrays. What if we have an array with custom keys (not a sequential list of integers…)?
We can solve this problem with the foreach construct. This construct is specifically designed to iterate over array items.
Info: The key-placeholder => part is placed into square brackets to indicate that this part of the construct is optional. The part can be omitted when we have no need of the key in the accompanying block but are only interested in the values…
<?php
$array = [ 1, 2, 'three', 'value' ];
print_r($array);
foreach( $array as $value ) {
echo "The obtained value is: `$value`\n";
}
# ---------------------------------------------------------------------------- #
$array = [
1 , 2, 3,
'key1' => 'value1',
100 => 'hello'
];
print_r($array);
foreach( $array as $key => $value ) {
echo "Key: `$key` has value: `$value`\n";
}
Sometimes (based on a condition) you want to skip a loop iteration or stop the loop prematurely. Tis can be accomplished by use of continue or break,
continueStop running the code in the current loop iteration and start the next iteration.
breakStop executing the loop iteration and break out of the loop.
issetThe isset function checks whether a PHP variable was created / assigned.
This function returns false if the tested variable isn’t declared before or is equal to null
emptyThe empty function checks whether a PHP variable has an empty value.
Examples of empty values: null, "", 0, …
<?php
echo "test undeclared variable\n";
var_dump( empty($some_variable) );
echo "\n";
echo "test declared variable\n";
$some_variable = "hello world";
var_dump( empty($some_variable) );
echo "\n";
echo "test empty variables\n";
$some_variable = "";
var_dump( empty($some_variable) );
$some_variable = 0;
var_dump( empty($some_variable) );
$some_variable = null;
var_dump( empty($some_variable) );strlenThe strlen function returns the length (number of characters) in a string.
str_splitThe str_split function parses a string into individual characters and returns an array where each item in the array corresponds to one character in the original string.
strtolowerThe strtolower returns a string with all alphabetic characters converted to lowercase.
strtoupperThe strtoupper returns a string with all alphabetic characters converted to uppercase.
explodeThe explode function parses a string into individual pieces based on a delimiter and returns an array where each item in the array corresponds to a section in the original string separated by the delimiter.
This function can be used to convert the lines in a file (retrieved via file_get_contents) into an array of lines.
<?php
$string = ">Random Sequence (250 nts sampled from ATGC)
GCCAATGGTATGTCAACTCAGTCTCCCCAACTCTCGTAACTGGTAGAAGG
GTGGAGCATGAATCATGCCATCCATCTCGTATTCGAATCCGTGCGCGCGG
AGCCGAATATTTAAGTATACACACCCGCAGCACGAGCATCGTACTTTGCC
TTTCCAGCATAATTATGCATGAGGTGATAGCGAGATGATTCGGGGTAATG
CCGTTGTACCCGGCCTCGGTCTTTCCGACGACGTCCCAACGCCGACACCA";
$lines = explode("\n", $string);
print_r( $lines );implodeThe implode function takes an array and glue as input. The items in the array will be glued together into a new string. Each of the sections in the new output string will be separated by the glue
preg_matchRegular expressions are a very powerful way of detecting patterns in a string.
The complete depth and power of regular expressions are out of the scope of this course but we will use them to detect header lines in multifasta sequences.
Create a script that:
php count-to-number.php 9Count up from 0 to 9:
0
1
2
3
4
5
6
7
8
9
Count down from 9 to 0:
9
8
7
6
5
4
3
2
1
0
Count up from 0 to 9 in steps of 3:
0
3
6
9
Create a script that prints a line of a asterisks * defined by a command line parameter.
php print-asterisks.php 9*********
Create a script that
* if one parameter is definedphp print-square-of-asterisks.php 9*********
*********
*********
*********
*********
*********
*********
*********
*********
php print-square-of-asterisks.php 15 5***************
***************
***************
***************
***************
Create a script that prints a left + bottom balanced triangle of asterisks with base defined by parameter.
php print-left-bottom-balanced-triangle.php 9*
**
***
****
*****
******
*******
********
Create a script that prints a right + bottom balanced triangle of asterisks with base defined by parameter.
php print-right-bottom-balanced-triangle.php 9 *
**
***
****
*****
******
*******
********
Create a script that prints a center + bottom balanced triangle of asterisks with base defined by parameter.
php print-center-bottom-balanced-triangle.php 9
**
****
******
********
Create al the triangles again but the base (maximum number of asterisks) should be on top instead of at the bottom…
php print-left-top-balanced-triangle.php 9*********
********
*******
******
*****
****
***
**
*
php print-right-top-balanced-triangle.php 9*********
********
*******
******
*****
****
***
**
*
php print-center-top-balanced-triangle.php 9*********
*******
*****
***
*
Create a script that counts the number of parameters provided
php count-argv.php 9 12 3 5 4 1 8 58 arguments where provided
Create a script that:
php number-statistics.php 9 12 3 5 4 1 8 5The numbers received:
number 0: 9
number 1: 12
number 2: 3
number 3: 5
number 4: 4
number 5: 1
number 6: 8
number 7: 5
Smallest number: 1
Avg: 5.875
Largest number: 12
Number of numbers: 8
Number occurences
9 -> 1
12 -> 1
3 -> 1
5 -> 2
4 -> 1
1 -> 1
8 -> 1
The numbers in reverse order:
number 7: 5
number 6: 8
number 5: 1
number 4: 4
number 3: 5
number 2: 3
number 1: 12
number 0: 9
Numbers from smallest to largest:
1
3
4
5
5
8
9
12
Create a script which stores the keys of an array as values of another array. (Extract the keys from an array)
php array-keys.php Array
(
[0] => position 1
[1] => position 2
[2] => 3
[3] => four
)
php array-reverse.php Array
(
[0] => 4
[1] => three
[2] => world
[3] => hello
)
Array
(
[four] => 4
[3] => three
[position 2] => world
[position 1] => hello
)
Create a script that generates the reverse complement of DNA string:
php dna-reverse-complement.php 'ATGCCGATAGGACTATGGACTATCTAGAGATCTATCAGAGAATATATCCGGGATAATCGGATATCGGCGATAC'orig.: ATGCCGATAGGACTATGGACTATCTAGAGATCTATCAGAGAATATATCCGGGATAATCGGATATCGGCGATAC
comp.: TACGGCTATCCTGATACCTGATAGATCTCTAGATAGTCTCTTATATAGGCCCTATTAGCCTATAGCCGCTATG
Bonus:
Print bonds:
php dna-reverse-complement-with-bonds.php 'ATGCCGATAGGACTATGGACTATCTAGAGATCTATCAGAGAATATATCCGGGATAATCGGATATCGGCGATAC'orig.: ATGCCGATAGGACTATGGACTATCTAGAGATCTATCAGAGAATATATCCGGGATAATCGGATATCGGCGATAC
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
comp.: TACGGCTATCCTGATACCTGATAGATCTCTAGATAGTCTCTTATATAGGCCCTATTAGCCTATAGCCGCTATG
Create a script that generates the reverse complement of DNA string and can cope with:
php dna-reverse-complement-robust.php 'ATgCXCgAtAgg ACTAtgGaCtA X TCtA g aGaTc TatCAgAgaatAtiXXATCcgggATAATcggAtATCggCGaTaC'orig.: ATgCXCgAtAgg ACTAtgGaCtA X TCtA g aGaTc TatCAgAgaatAtiXXATCcgggATAATcggAtATCggCGaTaC
comp.: TACGGCTATCCTGATACCTGATAGATCTCTAGATAGTCTCTTATATAGGCCCTATTAGCCTATAGCCGCTATG
Invalid NT characters:
X: 4 occurrences
i: 1 occurrences
Create a script that prints the nucleotide frequency of a DNA strand.
Additional: Create a simple bar plot to visualise the percentages.
php dna-frequency.php 'ATGCCGATAGGACTATGGACTATCTAGAGATCTATCAGAGAATATATCCGGGATAATCGGATATCGGCGATAC'input: ATGCCGATAGGACTATGGACTATCTAGAGATCTATCAGAGAATATATCCGGGATAATCGGATATCGGCGATAC
STATS:
A: 24 nts -> 32.876712328767 %
T: 18 nts -> 24.657534246575 %
G: 18 nts -> 24.657534246575 %
C: 13 nts -> 17.808219178082 %
GRAPH:
A: =================================
T: =========================
G: =========================
C: ==================
Create a script that prints the frequency of the characters in a string.
php character-frequency.php 'Hello world, this is a random 123#$ string.'input: Hello world, this is a random 123#$ string.
STATS:
'H': 1 occurences -> 2.3255813953488 %
'e': 1 occurences -> 2.3255813953488 %
'l': 3 occurences -> 6.9767441860465 %
'o': 3 occurences -> 6.9767441860465 %
' ': 7 occurences -> 16.279069767442 %
'w': 1 occurences -> 2.3255813953488 %
'r': 3 occurences -> 6.9767441860465 %
'd': 2 occurences -> 4.6511627906977 %
',': 1 occurences -> 2.3255813953488 %
't': 2 occurences -> 4.6511627906977 %
'h': 1 occurences -> 2.3255813953488 %
'i': 3 occurences -> 6.9767441860465 %
's': 3 occurences -> 6.9767441860465 %
'a': 2 occurences -> 4.6511627906977 %
'n': 2 occurences -> 4.6511627906977 %
'm': 1 occurences -> 2.3255813953488 %
'1': 1 occurences -> 2.3255813953488 %
'2': 1 occurences -> 2.3255813953488 %
'3': 1 occurences -> 2.3255813953488 %
'#': 1 occurences -> 2.3255813953488 %
'$': 1 occurences -> 2.3255813953488 %
'g': 1 occurences -> 2.3255813953488 %
'.': 1 occurences -> 2.3255813953488 %
Order by frequentie:
'H': 1 occurences -> 2.3255813953488 %
'e': 1 occurences -> 2.3255813953488 %
'w': 1 occurences -> 2.3255813953488 %
',': 1 occurences -> 2.3255813953488 %
'h': 1 occurences -> 2.3255813953488 %
'm': 1 occurences -> 2.3255813953488 %
'1': 1 occurences -> 2.3255813953488 %
'2': 1 occurences -> 2.3255813953488 %
'3': 1 occurences -> 2.3255813953488 %
'#': 1 occurences -> 2.3255813953488 %
'$': 1 occurences -> 2.3255813953488 %
'g': 1 occurences -> 2.3255813953488 %
'.': 1 occurences -> 2.3255813953488 %
'd': 2 occurences -> 4.6511627906977 %
't': 2 occurences -> 4.6511627906977 %
'a': 2 occurences -> 4.6511627906977 %
'n': 2 occurences -> 4.6511627906977 %
'l': 3 occurences -> 6.9767441860465 %
'o': 3 occurences -> 6.9767441860465 %
'r': 3 occurences -> 6.9767441860465 %
'i': 3 occurences -> 6.9767441860465 %
's': 3 occurences -> 6.9767441860465 %
' ': 7 occurences -> 16.279069767442 %
Order by character:
' ': 7 occurences -> 16.279069767442 %
'#': 1 occurences -> 2.3255813953488 %
'$': 1 occurences -> 2.3255813953488 %
',': 1 occurences -> 2.3255813953488 %
'.': 1 occurences -> 2.3255813953488 %
'H': 1 occurences -> 2.3255813953488 %
'a': 2 occurences -> 4.6511627906977 %
'd': 2 occurences -> 4.6511627906977 %
'e': 1 occurences -> 2.3255813953488 %
'g': 1 occurences -> 2.3255813953488 %
'h': 1 occurences -> 2.3255813953488 %
'i': 3 occurences -> 6.9767441860465 %
'l': 3 occurences -> 6.9767441860465 %
'm': 1 occurences -> 2.3255813953488 %
'n': 2 occurences -> 4.6511627906977 %
'o': 3 occurences -> 6.9767441860465 %
'r': 3 occurences -> 6.9767441860465 %
's': 3 occurences -> 6.9767441860465 %
't': 2 occurences -> 4.6511627906977 %
'w': 1 occurences -> 2.3255813953488 %
'1': 1 occurences -> 2.3255813953488 %
'2': 1 occurences -> 2.3255813953488 %
'3': 1 occurences -> 2.3255813953488 %