Embedding PHP

PHP is embedded in a HTML page using the as follows:

<?php
echo "Hello World";
?>;

CodePad Demo

Multiply lines of code can be enclosed in tags as follows:

<php
$first_name = "Martin";
echo "<h1>Welcome</h1>";
echo "<p>My name is {$first_name}</p>";
?>

CodePad Demo

Comments

Comments can be added to php code with the tags as follows:

Single line comments can be inserted using // as in C++.

<php // this is comment ?>

Single line comments can also be inserted with # as in Perl.

<php # this is comment ?>

Multi-line comments are inserted using /* …. */ as in C.

<php /*
This is
a multiline comment
*/ ?>

Variables

As hinted at above all variables must be named with a preceding $ sign.  Variable names are case sensitive.  In PHP there is no need to declare a data type on declaration, as PHP will assign a data type based on the variables content.

Variables can be of any length and can include letters, numbers and underscores.  They cannot however start with a number and are case-sensitive

To assign values to variables:

$myvar = 'Martin'; // Data Type: String
$myvar = "Martin"; // Data Type: String
$myvar = 1; // Data Type: integer
$myvar = 5.34; // Data Type: Double
$myvar = true; //Data Type: Boolean

Single or double quotes can be used in the variable declaration for strings.  If you echo a ‘true’ boolean it will output the value ‘1’.

Data types are set automatically but it is also possible to set the data type by type casting. For example:

$mystring = (string)"Hello";
$mynumberint = (int) 5;
$mynumberfloat = (float)3.4;
$myboolean = (boolean) true;

Advanced Note: PHP7 has introduced a ‘strict mode’ option that can be switched on if desired. This is designed to allow programmers to write better code as ‘fatal errors’ will be tripped if data types are not respected.

Almost all variables are local. Globals include a group of special variables called ‘super globals (more on which later).

Strings

When outputting the string using either echo or print() use double quotes.  Single quoted echo or print() command will not substitute any listed variables.

It is also recommended that variables are placed in braces {….} when placed in a string literal.

<php
$first_name = "Martin";
print ("My name is {$first_name}"); // outputs My Name is Martin
?>

Strings can also be concatenated ie one string added to another.

<php
$first_name = "Martin";
$last_name = "Cooper";
$full_name = $first_name . " " .$last_name;
print($full_name); // outputs Martin Cooper
?>

CodePad Demo

A period/dot is used as the concatenation character.

String Functions

substr() To return a sub-string, that is only part of the string, we can use the substr() function.  This accepts the string to be cut, the starting point and then the length of the sub-string.  The starting point begins at 0.

<php
echo substr('abcdef', 0, 4); // outputs abcd
echo substr('abcdefgh', 2, 6); // outputs cdefgh
$bigstring = "abcdefgh";
echo substr($bigstring, 2,2); // outputs cd
?>

CodePad Demo

The strpos() function returns the position of a specific character in a string.  The position count starts from 0.

<php
echo strpos('abc','c'); 
// outputs 2
?>

CodePad Demo

The str_shuffle() function randomly shuffles all the characters in a string.

<php
echo str_shuffle('This Makse sense');
// outputs Tkae hess snMise
?>

CodePad Demo

The str_replace() function can be used to replace a chosen string from another string.

<php
echo  str_replace('#',',','fred#bob#joe#');
    // outputs 'fred,bob,joe'
?>

CodePad Demo

The strlen() function will return the length of a string.

<php
$str = 'abcdef';
echo strlen($str); // 6
?>

Example

<php
	$fullname = "Bob Smith";;
    $spaceAt = strrpos($fullname , " ");
    $firstname = substr($fullname, 0, $spaceAt);
    $surname = substr($fullname, $spaceAt);
?>

See http://www.w3schools.com/PHP/php_ref_string.asp for a list of other useful string functions.

Numbers

To assign a numeric variable use the same syntax as that for strings but without using double or single quotes.  Numeric values can be integers (whole numbers) or floats (decimal numbers).

Numbers can be manipulated through standard mathematical operators like +, -, *, / and there are also a host of mathematical functions.  For example ‘round()’ can be used to round a decimal number to the nearest integer.

<php
$price = 5.55;
$price2= round($price);
print($price2); //outputs 6
?>

CodePad Demo

We can also set the output to a set number of decimal places by placing an additional parameter after the number.

<php
$price = 5.55;
$price2= round($price, 1);
print($price2); // outputs 5.6
?>

CodePad Demo

Number Functions

As with strings there are a range of built in functions for manipulating numbers.

The number_format() function can be used to add commas to numbers over a thousand as commonly used when writing large numbers.

<php
$price = 56000;
print(number_format($price)); // outputs 56,000
?>

CodePad Demo

We can also use number_format() for displaying decimal places ie:

<php
$price = 1.252525;
print(number_format($price, 2)); // outputs 1.25
?>

CodePad Demo

The round() function returns a decimal to the nearest integer.

<php
echo round(0.60);
// outputs 1
?>

CodePad Demo

The floor() function rounds down a decimal to an integer.

<php
echo floor(0.60);
// outputs 0
?>

CodePad Demo

The ceil() function will round up a decimal to an integer.

<php
echo ceil(1.05);
// outputs 2
?>

CodePad Demo

The max() function returns the number with the highest value of two specified numbers.

<php
echo max(1.05, 20);
// outputs 20
?>

CodePad Demo

The min() function returns the number with the lowest value of two specified numbers.

<php
echo min(1.05, 20);
// outputs 1.05
?>

CodePad Demo

See http://www.w3schools.com/PHP/php_ref_math.asp for a list of other useful number/math functions.

Booleans

Boolean Variables Yes/No, True/False, 1/0 (1 = true, 0 = false) can be assigned with the ‘true’ and ‘false’ keywords ie

<php
$onoff = true;
echo $onoff;
?>

CodePad Demo

Constants

Constants can be created in PHP.  A constant is a value that is set once for the course of a particular script.  Constants are created using the define() function.  It is also convention that your constant name appears in uppercase.  With constants there is no need for the preceding $ sign.

<php
define("RATE", 0.75);
echo RATE;
?>

CodePad Demo

Form and URL – The Super Globals

One of the key features of web applications is the ability to pass data from one page in your web site to another.  One method to do this is HTML forms.

A HTML form is sent for processing using either a ‘post’ or ‘get’ method.  The values that the user entered in the form are then available to the targeted action page for processing.  In a HTML form each form element should have a unique name/id.  This is the fieldname of the value to be submitted.

<input name="email" type="text" id="email">

That is the name of the name/value pairs that will get submitted when the data is sent.  Ie if you have a form field named ‘email’ and the users enters the email ‘fred@bloggs.co.uk’ the name/value pair submitted is equal to email=fred@bloggs.co.uk.

In PHP the values are made available to the receiving page.  How they are retrieved depends on which method was used to send the data in the form ie post or get.

  • $_POST['fieldname'] – retrieves values from a HTML form that has used the method ‘’post’.
  • $_GET['fieldname'] – retrieves values from a HTML form that has used the method ‘get’.

$_POST Demo

$_GET Demo

Tip: ($_POST and $_GET  are known as superglobal variables.)

The HTML form method ‘post’ sends the name/values pairs to the next page in the header of the http page request.  As such the values are hidden from the user.  The ‘get’ methods places the name/values pairs in URL of the page request ie:

http://www.mysite.com/process.php?email=fred@bloggs.co.uk

Multiply values will be concatenated in the URL with ampersands as follows:

http://www.mysite.com/process.php?email=fred@bloggs.co.uk&name=Fred

This is what is known as a querystring.  A querystring can be created by appending a HTML link with a ‘?’ and then the name/value pair.  As indicated multiply values can be sent by using the ‘&’ concatenation character.

Query String Demo

Note: :  These techniques of transferring variables in the FORM and URL are not unique to PHP but also used by other server side scripts such as ASP.NET, JSP and Coldfusion.

Writing to the Screen, echo, print() and printf()

In PHP the built-in functions ‘echo’, ‘print()’ and ‘printf()’ can be used output values in the HTML.  All three can be used to output HTML tags to the browser.  They differ as follows:

Outputting to the Screen with echo

Use echo to output a simple string or variable value.  It also takes a comma separated list of strings and/or variables.  Whitespacing most be explicitly expressed.  Parenthesis are not required.

Examples:

<php echo "Today I won £", 5;?>
<php $prize = 5 ;?>
<php echo "Today I won £", $prize, "in the raffle";?>

CodePad Demo

You can use double or single quotes ie:

<php echo 'Today I won £', 5;?>
<php $prize = 5 ;?>
<php echo 'Today I won £', $prize;?>

CodePad Demo

Outputting to the Screen with print()

Use print() when only one argument is to be output.  Again double or single quotes can be used and if necessary escaped with a backslash

<php
print ('This works');
print ("So does this");
print ('and can be \'escaped\'.');
print ("I can \"escape\" too.");
/*
print ("Today I won £", $prize);// this will throw an error as it has 2 paramaters
*/
?>

CodePad Demo

When using double quotes a \n can be used to add line breaks.  Ie

<php print "<ul>\n<li>1</li>\n<li>2</li>\n<li>3</li>\n</ul>";?>
//outputs a nicely formatted HTML list
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>

CodePad Demo

Variables in print and echo using Braces

It is recommended that variables with echo and/or print are placed in braces {……}.  When using braces ensure that string literals are placed in double quotes not single quotes.

<php
$myvar4 = 15;
echo "I won £{$myvar4}<br>"; // outputs I won £15
echo 'I won £{$myvar4} - single quotes variable NOT substituted<br>';
print "I won £{$myvar4}<br>"; // outputs I won £15
print 'I won £{$myvar4} - single quotes variable NOT substituted<br>';
?>

CodePad Demo

2 Thoughts to “PHP Basics”

  1. Sol Rana

    The function substr() in String Functions section has a problem. Because in the last line of code the bracket is being closed without opening bracket after variable $bigstring.
    The code is below.
    echo substr($bigstring), 2,2); // outputs cd

    1. admin

      Hi Thanks for letting me know – should be fixed now – check out the CodePen

Leave a Comment