PHP Basics

PHP is a widely-used general-purpose scripting language that is especially suited for Web development and can be embedded into HTML.

source: php.net

This means PHP can be used to generate HTML. This allows us to adhere to the DRY (Don’t Repeat Yourself) principle.

What makes a PHP-script

A PHP-script is identified by its .php extension and the PHP-tags in the file.

PHP tags

PHP interprets only the code enclosed within the special PHP-tags.

  • Opening tag: <?php
  • Closing tag: ?>

php-basics/php-tags | src

echo "Before php-tags";

<?php

echo "Within php-tags\n";

?>

echo "After php-tags";

output of php-basics/php-tags

echo "Before php-tags";

Within php-tags

echo "After php-tags";

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:

{{ instruction }};

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 }

Comments

Single line comments

PHP will ignore everything behind a # or //.


echo 'hello world';

// ignore this

# and ignore this

echo 'by world';

Multi-line comments

PHP will ignore everything enclosed by /* and */.


echo 'hello world';

/* ignore this

and ignore this */

echo 'by world';

Execute a PHP-script

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:

php <script-to-execute>.php

The above command will print the output to the STDOUT.

Hello World

The obligatory hello world.

Create a file: hello-world.php with content:

php-basics/hello-world | src

<?php

echo "Hello World";

?>

output of php-basics/hello-world

Hello World
Info: The echo statement prints a string. See echo for more info

Info: If you get a command not found error, you probably have to install php. Run: sudo dnf install php

Run it via:

php hello-world.php

on the command line.

Types and variables

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.

$name = 'value to store';
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:

  • scalars
  • arrays

Scalars

A scalar variable can hold an atomic quantity. For example: one string, or one number, …

Types

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

Declare

Assign a value to a variable:

Generic syntax:

$varname = 'value to store';

Examples:

$int    = 123;
$float  = 4.56;
$string = 'Hello World';
$true   = true;
$false  = false;

Printing/Displaying scalars

A scalar can be printed via two methods:

Echo

Generic syntax:

echo <scalar>;
echo <scalar1>, <scalar2>, ...;

Echo outputs the provided scalars.

Multiple scalars can be printed at once, just separate them by a comma ,.

Example:

echo 123;
echo 4.56;
echo 'Hello World';
echo true;
echo false;
Print

Generic syntax:

print( <scalar> );

Print can only output one scalar at the time. (This can be circumvented via concatenation…)

Example:

print( 123 );
print( 4.56 );
print( 'Hello World' );
print( true );
print( false );

String concatenation and interpolation Or single vs. double quotes

Scalars can be combined, concatenated into larger strings.

The concatenation symbol is a dot: ..

php-basics/concatenate | src

<?php

print( 'This is a string' . ' || '  . 'this is a number: '  . 42 );

output of php-basics/concatenate

This is a string || this is a number: 42

You may have already noticed that printing variables enclosed by single quotes ' doesn’t work. The literal variable name is printed instead.

php-basics/variables-in-single-quotes | src

<?php

$variable = 'Hello World';

echo 'The variable contains: $variable!';

output of php-basics/variables-in-single-quotes

The variable contains: $variable!

To instruct PHP to interpret the variables, and other special sequences, the string must be enclosed by double quotes: ".

php-basics/variables-in-double-quotes | src

<?php

$variable = 'Hello World';

echo "The variable contains: $variable!";

output of php-basics/variables-in-double-quotes

The variable contains: Hello World!
Special character sequences

The following special character sequences are interpreted by PHP and formatted accordingly…

Sequence Result
\n New line
\r New line (Windows)
\t The literal -character
\$ Literal $ (escaping prevents variable interpreation)
\" Literal " (escaping prevents string termination).

Example:

php-basics/escape-sequences | src

<?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";

output of php-basics/escape-sequences

1. The value of the variable is: hello world.2. The value of the variable is: hello world.
    3. The value of the variable is: hello world.
4. The value of the variable is: $variable.
5. The value of the variable is: "hello world".

Basic arithmetic

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:

php-basics/arithmetic | src

<?php

$a = 42;
$b = 3.1415;
$c = 5;

echo $a + $b  . "\n";
echo $a - $b  . "\n";
echo $a * $b  . "\n";
echo $a / $b  . "\n";
echo $a % $c  . "\n";
echo $a ** $c . "\n";

output of php-basics/arithmetic

45.1415
38.8585
131.943
13.369409517746
2
130691232

Arrays

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.

Declare

An array can be declared in two ways:

$array = array( /* list of array items */ );

$array = [ /* list of array items */ ];

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

php-basics/array-auto-increment | src

<?php

$array = [1,2,3];

print_r($array);

$array[] = 'hello';

print_r($array);

output of php-basics/array-auto-increment

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => hello
)

The keys can however be specified manually:

php-basics/array-custom-keys | src

<?php

$array = [
   'key1' => 'value1',
   'two'  => 2,
   3      => 'hello world',
];

print_r($array);

output of php-basics/array-custom-keys

Array
(
    [key1] => value1
    [two] => 2
    [3] => hello world
)

Print/Display arrays

The function print_r can be used to print an array.

Generic syntax:

print_r( $array );

php-basics/print_r | src

<?php

$array = array(
   'one' => 1,
   'two' => 'three',
   4     => 'four',
   'hello' => 'world'
);

print_r( $array );

output of php-basics/print_r

Array
(
    [one] => 1
    [two] => three
    [4] => four
    [hello] => world
)

Get a value from an array

A value can be retrieved by specifying the array variable name followed by the index you wish to retrieve enclosed in square brackets:

$array[<key>];

If the key is a string, the appropriate quoting must be used.

$array['<key>'];

Example:

php-basics/array-get-key | src

<?php

$array = [1,2,3];

echo $array[0] . "\n";
echo $array[1] . "\n";
echo $array[2] . "\n";

$array_assoc = [
   'key1' => "value1",
   'key2' => "value2",
   'key3' => "value3",
];

echo $array_assoc['key1'] . "\n";
echo $array_assoc['key2'] . "\n";
echo $array_assoc['key3'] . "\n";

output of php-basics/array-get-key

1
2
3
value1
value2
value3

Update a value in an array

An array value can be targeted by its key. This key can also be used to update the value:

$array[<key>] = <new value>;

Example:

php-basics/array-update-value | src

<?php

$array = [
   "value1",
   "value2",
   "value3",
   100 => "hundred",
   'key' => "value",
];

print_r($array);

$array['key'] = "new value for key";

$array[1] = 'index 1 now points here';

print_r($array);

output of php-basics/array-update-value

Array
(
    [0] => value1
    [1] => value2
    [2] => value3
    [100] => hundred
    [key] => value
)
Array
(
    [0] => value1
    [1] => index 1 now points here
    [2] => value3
    [100] => hundred
    [key] => new value for key
)

Manipulating arrays

Add an item to the end of an array:

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;).

php-basics/array-append | src

<?php

$array = [1,2,3];

print_r( $array );

array_push( $array, 4);

print_r( $array );

// or

$array[] = 5;

print_r( $array );

output of php-basics/array-append

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
Add an item in front of an array:

Adding an element in front of an array can be accomplished by the function array_unshift.

php-basics/array-prepend | src

<?php

$array = [1,2,3];

print_r( $array );

array_unshift( $array, 4 );

print_r( $array );

output of php-basics/array-prepend

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Array
(
    [0] => 4
    [1] => 1
    [2] => 2
    [3] => 3
)
Extract the first element from an array

Extracting the first element from an array can be accomplished by the function array_shift.

php-basics/array-shift | src

<?php

$array = [1,2,3];

print_r( $array );

echo array_shift( $array ) . "\n";

print_r( $array );

output of php-basics/array-shift

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)
1
Array
(
    [0] => 2
    [1] => 3
)
Extract the last element from an array

Extracting the last element from an array can be accomplished by the function array_pop.

php-basics/array-pop | src

<?php

$array = [1,2,3];

print_r( $array );

echo array_pop( $array ) . "\n";

print_r( $array );

output of php-basics/array-pop

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)
3
Array
(
    [0] => 1
    [1] => 2
)
Count the elements in an array

Counting the elements in an array can be accomplished by the function count.

php-basics/array-count | src

<?php

$array = [ 1, 2, 3 ];

echo count($array) . "\n";

$array[] = "Add item";

echo count($array) . "\n";

array_shift( $array );
array_shift( $array );

echo count($array) . "\n";

output of php-basics/array-count

3
4
2

Special arrays

PHP has some special, reserved, arrays. These arrays are created and filled by PHP.

$argv

This array holds all the arguments passed to a PHP-script from the command line.

php print_r-argv.php 'arg1' 'arg2' 123 --options
Array
(
    [0] => print_r-argv.php
    [1] => arg1
    [2] => arg2
    [3] => 123
    [4] => --options
)
Info: Notice that the first argument in this array is always the name of the script!

$_GET

The $_GET-array holds data sent to a webpage via a HTTP-get method.

This corresponds with URL parameters.

http://example.com/page.php?arg1=hello&arg2=world&end=!
Array
(
    [arg1] => hello
    [arg2] => world
    [end] => !
)

$_POST

The $_POST-array holds data sent to a webpage via a HTTP-post method.

This is typically done via a from submission…

$_SESSION

You can store inter-page data in the $_SESSION reserved array.

This inter-page data is typically:

  • user info
  • preferences

$_FILES

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
        )
)

Conditionals

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 {}).

if( /* <condition> */ ) {

    /* execute this code here */
}

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*/
}

Comparison operators

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-basics/type-juggling | src

<?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 );

output of php-basics/type-juggling

string(13) "1 as a string"
int(1)
bool(true)
bool(true)
bool(true)
bool(false)
bool(false)
bool(false)
Info: var_dump prints a variable with type information

Logical operators

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-basics/logical-operators | src

<?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";
}

?>

output of php-basics/logical-operators

`true or false` evaluated to TRUE
----------------------------------------------------------------------
`!true` evaluated to FALSE
----------------------------------------------------------------------
`true and false` evaluated to FALSE

These logical operators can be combined at will. Brackets () can be used to enforce precedence.

php-basics/logical-precedence | src

<?php

if( ( 1 and 0 ) and true ) {
   echo "`( 1 and 0 ) and true` --> true\n";
}
else {
   echo "`( 1 and 0 ) and true` --> false\n";
}

if( 1 and ( 0 and true ) ) {
   echo "`1 and ( 0 and true )` --> true\n";
}
else {
   echo "`1 and ( 0 and true )` --> false\n";
}

output of php-basics/logical-precedence

`( 1 and 0 ) and true` --> false
`1 and ( 0 and true )` --> false

Loops

Loops enable you to repeat a block of code until a condition is met.

While

This construct will repeat until the defined condition evaluates to false:

while( /* <condition> */ ) {

    /* execute this block */
}
Warning: Incorrectly formatted code can result in an endlessly running script. If this happens, use Ctrl+c on the command line to abort the running script.

Danger: The never ending loop:

# This will run until interrupted by the user.

while(1) {

    echo "Use `Ctrl`+`c` to abort this loop\n";
}

php-basics/loops-while | src

<?php

$iterations = 10;

while( $iterations > 0 ) {

   echo "Countdown finished in $iterations iterations\n";
   $iterations = $iterations - 1;
}

output of php-basics/loops-while

Countdown finished in 10 iterations
Countdown finished in 9 iterations
Countdown finished in 8 iterations
Countdown finished in 7 iterations
Countdown finished in 6 iterations
Countdown finished in 5 iterations
Countdown finished in 4 iterations
Countdown finished in 3 iterations
Countdown finished in 2 iterations
Countdown finished in 1 iterations

Info: The pattern $variable = $variable + 1 is used a lot in programming. Therefore shorthand versions of this, and similar operations, are available:

$var = 1;

# Add or substract by 1:
$var++; // increment by 1
$var--  // decrement by 1

# Add or substract by n:
# $var += n;
# $var -= n;

$var += 3;
$var += 100;
$var -= 42;
$var -= 4;

Exercise:

  • Make a script that counts from 0 to 10
  • Modify the script to count from 50 to 60
  • Modify the script to count from 0 to 10 and back to 0
  • Modify the script to count from 0 to 30 in steps of 3.

Only while loops are allowed.

For

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.

for( <init counter>; <condition>; <increment counter> ) {

    /* execute this block */
}

Notice the semi-colons ; between each of the for-parts!

php-basics/loops-for | src

<?php

for( $counter = 0; $counter < 10; $counter++ ) {

   echo "Loop interation: $counter\n";
}

output of php-basics/loops-for

Loop interation: 0
Loop interation: 1
Loop interation: 2
Loop interation: 3
Loop interation: 4
Loop interation: 5
Loop interation: 6
Loop interation: 7
Loop interation: 8
Loop interation: 9

Exercise:

  • Make a script that counts from 1 to 10
  • Modify the script to count from 0 to 10 and back to 0
  • Modify the script to count from 0 to 30 in steps of 3.

Only for loops are allowed.

The for construct can also be used to loop over all elements in an array:

php-basics/loops-for-array | src

<?php

$array = [
   1,
   2,
   'three',
   'value'
];

print_r($array);

for( $i = 0; $i < count($array); $i++ ){

   echo "\$array has value: '". $array[$i] . "' at index $i\n";
}

output of php-basics/loops-for-array

Array
(
    [0] => 1
    [1] => 2
    [2] => three
    [3] => value
)
$array has value: '1' at index 0
$array has value: '2' at index 1
$array has value: 'three' at index 2
$array has value: 'value' at index 3

Exercise:

  • Fill an array with: [ one, two, three, four, five ];
  • Print each word on a single line.
  • Modify the script to also print the index before the word: $index: $value

Foreach

The 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.

foreach( <array> as [<key-placeholder> =>] <value-placeholder>) {

    /* use key and value here*/
}

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-basics/loops-foreach | src

<?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";
}

output of php-basics/loops-foreach

Array
(
    [0] => 1
    [1] => 2
    [2] => three
    [3] => value
)
The obtained value is: `1`
The obtained value is: `2`
The obtained value is: `three`
The obtained value is: `value`
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [key1] => value1
    [100] => hello
)
Key: `0` has value: `1`
Key: `1` has value: `2`
Key: `2` has value: `3`
Key: `key1` has value: `value1`
Key: `100` has value: `hello`

Flow control

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,

continue

Stop running the code in the current loop iteration and start the next iteration.

php-basics/continue | src

<?php

echo "Loop start\n";

for( $count = 0 ; $count < 10 ; $count++ ) {


   if( $count == 3 or $count == 6 ) {

      echo "Count is 3 or 6; start next iteration...\n";
      continue;
   }

   echo "Current count == $count\n";
}

echo "Loop end\n";

output of php-basics/continue

Loop start
Current count == 0
Current count == 1
Current count == 2
Count is 3 or 6; start next iteration...
Current count == 4
Current count == 5
Count is 3 or 6; start next iteration...
Current count == 7
Current count == 8
Current count == 9
Loop end

break

Stop executing the loop iteration and break out of the loop.

php-basics/break | src

<?php

echo "Loop start.\n";

for( $count = 0 ; $count < 10 ; $count++ ) {


   if( $count == 3 ) {

      echo "Count is 3: stop this loop...\n";
      break;
   }

   echo "Current count == $count\n";
}

echo "Loop end.\n";

output of php-basics/break

Loop start.
Current count == 0
Current count == 1
Current count == 2
Count is 3: stop this loop...
Loop end.

Commonly used (builtin) functions

isset

The 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

php-basics/isset | src

<?php

echo "test undeclared variable\n";
var_dump( isset($some_variable) );
echo "\n";

echo "test declared variable\n";
$some_variable = "hello world";
var_dump( isset($some_variable) );
echo "\n";

echo "test null variable\n";
$some_variable = null;
var_dump( isset($some_variable) );

output of php-basics/isset

test undeclared variable
bool(false)

test declared variable
bool(true)

test null variable
bool(false)

empty

The empty function checks whether a PHP variable has an empty value.

Examples of empty values: null, "", 0, …

php-basics/empty | src

<?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) );

output of php-basics/empty

test undeclared variable
bool(true)

test declared variable
bool(false)

test empty variables
bool(true)
bool(true)
bool(true)

strlen

The strlen function returns the length (number of characters) in a string.

php-basics/strlen | src

<?php

$string =  "The length of this string is: ";
echo $string;
echo strlen( $string );

output of php-basics/strlen

The length of this string is: 30

str_split

The 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.

php-basics/str_split | src

<?php

$string = "split into chars";

$array_of_chars = str_split( $string );

print_r( $array_of_chars );

output of php-basics/str_split

Array
(
    [0] => s
    [1] => p
    [2] => l
    [3] => i
    [4] => t
    [5] =>  
    [6] => i
    [7] => n
    [8] => t
    [9] => o
    [10] =>  
    [11] => c
    [12] => h
    [13] => a
    [14] => r
    [15] => s
)

strtolower

The strtolower returns a string with all alphabetic characters converted to lowercase.

php-basics/strtolower | src

<?php

$string =  "This is a MIXED case string";
echo $string;
$string = strtolower( $string );
echo $string;

output of php-basics/strtolower

This is a MIXED case stringthis is a mixed case string

strtoupper

The strtoupper returns a string with all alphabetic characters converted to uppercase.

php-basics/strtoupper | src

<?php

$string =  "This is a MIXED case string";
echo $string;
$string = strtoupper( $string );
echo $string;

output of php-basics/strtoupper

This is a MIXED case stringTHIS IS A MIXED CASE STRING

explode

The 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.

php-basics/explode | src

<?php

$string = "This is the first section of a semicolon separated string;This is the second section;And this the third!";

$array_of_sections = explode(";", $string);

print_r( $array_of_sections );

output of php-basics/explode

Array
(
    [0] => This is the first section of a semicolon separated string
    [1] => This is the second section
    [2] => And this the third!
)

This function can be used to convert the lines in a file (retrieved via file_get_contents) into an array of lines.

php-basics/explode-newline | src

<?php

$string = ">Random Sequence (250 nts sampled from ATGC)
GCCAATGGTATGTCAACTCAGTCTCCCCAACTCTCGTAACTGGTAGAAGG
GTGGAGCATGAATCATGCCATCCATCTCGTATTCGAATCCGTGCGCGCGG
AGCCGAATATTTAAGTATACACACCCGCAGCACGAGCATCGTACTTTGCC
TTTCCAGCATAATTATGCATGAGGTGATAGCGAGATGATTCGGGGTAATG
CCGTTGTACCCGGCCTCGGTCTTTCCGACGACGTCCCAACGCCGACACCA";

$lines = explode("\n", $string);

print_r( $lines );

output of php-basics/explode-newline

Array
(
    [0] => >Random Sequence (250 nts sampled from ATGC)
    [1] => GCCAATGGTATGTCAACTCAGTCTCCCCAACTCTCGTAACTGGTAGAAGG
    [2] => GTGGAGCATGAATCATGCCATCCATCTCGTATTCGAATCCGTGCGCGCGG
    [3] => AGCCGAATATTTAAGTATACACACCCGCAGCACGAGCATCGTACTTTGCC
    [4] => TTTCCAGCATAATTATGCATGAGGTGATAGCGAGATGATTCGGGGTAATG
    [5] => CCGTTGTACCCGGCCTCGGTCTTTCCGACGACGTCCCAACGCCGACACCA
)

implode

The 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

php-basics/implode | src

<?php

$array_of_sections = [
   "section 1",
   "section 2",
   "section 3",
   "section 4",
];

echo "Create a new string delimited by semicolons: \n";
echo implode(";", $array_of_sections);

echo "\n";
echo "Create a new string delimited by newlines: \n";
echo implode("\n", $array_of_sections);

output of php-basics/implode

Create a new string delimited by semicolons: 
section 1;section 2;section 3;section 4
Create a new string delimited by newlines: 
section 1
section 2
section 3
section 4

preg_match

Regular 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.

php-basics/preg_match | src

<?php

echo "We want to match a leading > symbol:\n";
//       Pattern  Find pattern in this
var_dump( preg_match("/^>/",  ">MultiFasta Sequence Header") );

var_dump( preg_match("/^>/",  "Hello World") );

output of php-basics/preg_match

We want to match a leading > symbol:
int(1)
int(0)

Exercises

Exercise:

Create a script that:

  • receives a number from the command line
  • counts from zero to this number
  • counts back from this number to zero
  • counts from zero to the number in steps of three
php count-to-number.php 9
Count 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

Exercise:

Create a script that prints a line of a asterisks * defined by a command line parameter.

php print-asterisks.php 9
*********

Exercise:

Create a script that

  • prints a square of a asterisks * if one parameter is defined
  • Prints a block with width and height if both parameters are defined.
php print-square-of-asterisks.php 9
*********
*********
*********
*********
*********
*********
*********
*********
*********

php print-square-of-asterisks.php 15 5
***************
***************
***************
***************
***************

Exercise:

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
*
**
***
****
*****
******
*******
********

Exercise:

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
        *
       **
      ***
     ****
    *****
   ******
  *******
 ********
 

Exercise:

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
     
    **
   ****
  ******
 ********

Exercise:

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
*********
 *******
  *****
   ***
    *

Exercise:

Create a script that counts the number of parameters provided

php count-argv.php 9 12 3 5 4 1 8 5
8 arguments where provided

Exercise:

Create a script that:

  • reads a list of numbers from the command line
  • prints the list
  • prints the number of numbers (count)
  • calculates/prints the min, max and average of the numbers
  • Print how many times a number occurs in the list
  • (prints the list backwards (bonus))
  • (prints the list sorted (bonus))
php number-statistics.php 9 12 3 5 4 1 8 5
The 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

Exercise:

Create a script which stores the keys of an array as values of another array. (Extract the keys from an array)

$array = array(
    'position 1' => 'hello',
    'position 2' => 'world',
    3            => 'three',
    'four'       => 4
);
php array-keys.php 
Array
(
    [0] => position 1
    [1] => position 2
    [2] => 3
    [3] => four
)

Exercise:

  • Create a script which reverses an array.
  • Create a script which reverses an array and preserves the keys
$array = array(
    'position 1' => 'hello',
    'position 2' => 'world',
    3            => 'three',
    'four'       => 4
);
php array-reverse.php 
Array
(
    [0] => 4
    [1] => three
    [2] => world
    [3] => hello
)
Array
(
    [four] => 4
    [3] => three
    [position 2] => world
    [position 1] => hello
)

Exercise:

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
Info: The PHP functions: str_split amd strlen can be of use.

Exercise:

Create a script that generates the reverse complement of DNA string and can cope with:

  • with Caps and non caps letters
  • white space
  • unvalid nucleotides (and report these)
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

Exercise:

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: ==================

Exercise:

Create a script that prints the frequency of the characters in a string.

  • sort by frequency: low to hight + high to low
  • sort by character (and reverse)
  • case-insensitive (bonus)
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 %

Info: See: sort, asort, ksort,… for different sort functions