PHP introduction


by - posted

Overview
PHP introduction

PHP introduction : PHP stands for PHP Hypertext Preprocessor (while PHP originally stood for Personal Home Page).

PHP is an open source general-purpose server-side scripting language originally designed for Web development to produce dynamic Web pages. It is one of the first developed server-side scripting languages to be embedded into an HTML source document rather than calling an external file to process data. The code is interpreted by a Web server with a PHP processor module which generates the resulting Web page. (from Wikipedia)

How does PHP work

The server first reads the PHP file carefully in order to see if there are any tasks that need to be executed. Only after the server has done what it is supposed to do, the result is sent to the client. It is important to understand that the client only sees the result of the server’s work, not the actual instructions.
This means that if you click “view source” on a PHP page, you do not see the PHP codes – only basic HTML tags. Therefore, you cannot see how a PHP page is made by using “view source”.

Server on your PC

XAMPP is a server you can basically install on your PC in order to run/test PHP programs locally.
Link to XAMPP
XAMPP stands for Cross-Platform (X), Apache (A), MariaDB (M), PHP (P) and Perl (P).

PHP in a HTML file

You can put the PHP code in any place of your HTML file in the <body> section.

<!DOCTYPE html>
<html>
<head>
<title>put a relevant title here</title>
</head>
<body>
<?php echo "hello world"; ?>
</body>
</html>

PHP in an external file

You have the possibility to put your PHP code in an external file.
Let’s name the external file “example.php”

example.php contains <?php echo "hello world"; ?>

You can execute this PHP file in calling it from any place (in the body) of a HTML file like this :

<!DOCTYPE html>
<html>
<head>
<title>put a relevant title here</title>
</head>
<body>
<?php include("example.php"); ?>
</body>
</html>

Comments

<?php
/* this is
a
multi line
comment
*/
// this is a single line comment
?>

Variables

Introduction (from w3schools)

In PHP, a variable does not need to be declared before adding a value to it. A variable is created the moment you first assign a value to it.

Rules :
– Variables in PHP starts with a $ sign, followed by the name of the variable
– The variable name must begin with a letter or the underscore character
– A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
– A variable name should not contain spaces
– Variable names are case sensitive (y and Y are two different variables)

The life cycle

Before a variable is used, it has no existence. It is unset. So isset() is false.

$var;
$checked = isset($var);

The first time a variable is used, it’s automatically created. It also receives a type according to the assignment. Now isset() is true.

$a = 1;
$b = 1.0;
$c = ‘text’;
$d = $animal[‘unicorn’] = ‘pink unicorn’;

Setting an existing variable to null ( $var = null; ) is a way of un-setting a variable.
Another way is by using the unset() construct.
Un-set variables are also empty. So empty() is true.

The empty values are for :
– booleans             FALSE              $x = FALSE;
– integers and floats  zero           $a = 0;
– strings              empty string     $c = ”;
– arrays              empty array       $d = array();

The scope

The scope of a variable in PHP is the context in which the variable was created, and in which it can be accessed.

PHP has different variable scopes:
– global
– superglobal
– local
– static
– parameter

– Global
Global scope refers to any variable that is defined outside of any function.
Global variables can be accessed from any part of the script that is not inside a function.
To access a global variable from within a function, use the “global” keyword.

– Superglobal
Superglobals are a special set of predefined global arrays containing various useful information. They are accessible from anywhere in your script (including inside functions). Examples $_GET, $_POST, $_SESSION, $_SERVER …

– Local
A variable declared within a PHP function is local and can only be accessed within that function.
Local variables are deleted as soon as the function is completed.

– Static (local)
When a function is completed, all of its variables are normally deleted. However, sometimes you want a local variable to not be deleted. Use the “static” keyword when you declare the variable. In this case, each time the function is called, the variable will still have the information it contained from the last time the function was called.

– Parameter (local)
A parameter is a local variable whose value is passed to the function by the calling code.
Parameters are declared in a parameter list as part of the function declaration. Parameters are also called arguments.

Data types

String

String variables are used for values that contain characters.

$txt="Hello World"; is the same as $txt='Hello World';

– The anti slash

The anti slash is a must if you use equal signs in a string for the PHP interpreter !

$var = "My \"name\" is Marc";    but    $var = 'My "name" is Marc';
$var = 'Je m\'appelle Marc';     but    $var = "Je m'appelle Marc";

Integer

An integer is any positive or negative whole number or zero.

$age = 18;

Float

$something = 18.56;

Boolean

$i_am_a_hero = true;
$i_am_a_hero = false;

NUL

$var = NULL; is the same as  $var = null;

Operators

Arithmetic

addition           c = a + b
subtraction      c = a – b
multiplication  c = a * b
division             c = a / b
modulus           c = a % b     c will be the reminder of a divided by b
negation           -c                 opposite of c

Incrementing / decrementing

pre-increment     a++
post-increment    ++a
pre-decrement     a–
post-decrement    –a

Comparison

equal              a == b           value
not equal        a <> b or a!=b
identical         a===b            value and type
not identical   a!==b
greater than   a > b
greater or equal a>=b
less than             a < b
less or equal       a<=b

Logical

AND          a and b    or  a&&b       True if both a and b are true
OR            a or b       or  a||b         True if either or both a and b are true
XOR          a xor b                            True if either a or b is true, but not both
NOT          ! a                                   True if a is not true. Example : !(4==7) returns true

Assignment

a gets the value of b        a = b
addition                            a += b                a = a + b
subtraction                       a -= b                a = a – b
multiplication                   a *= b               a = a * b
division                             a /= b                a = a / b
modulus                           a %= b               a = a % b
concatenate two strings  a .= b                a = a . b

String

concatenation        a . b            Example “Hi” . “John” gives HiJohn

Array

union            x + y                          Union of x and y
equality        x == y                        True if x and y have the same key/value pairs
identity         x === y                      True if x and y have the same key/value pairs in the same order and are of the same type
inequality      x != y    or x <> y    True if x is not equal to y
non-identity  x !== y                     True if x is not identical to y

Output

Version 1

<?php
$age = 18;
echo "your age is $age years";
?>

Version 2

Is the mostly used by PHP programmers

<?php
$age = 18;
echo ' your age is ' . $age . 'years';
?>

The newline “trick”

echo 'after this text there will be a new line' . '<br>';
echo 'this text will be on the new line' ;

The print command

print_r();

Combinations (variable, text, HTML)

echo "$tmpemail is <strong>NOT</strong> a valid email address.<br/>";

User input and $_POST

A way that allows the user to supply your PHP script with input is done by using HTML forms.

The HTML form (for user input)

<html>
<head>
</head>
<body>
<form action="yourScript.php" method="post">
<input type="text" name="clientName"><br>
<input type="submit" value="submit">
</form>
</body>
</html>

The PHP script (yourScript.php)

Get the variable from the superglobal $_POST, then assign it to a variable in the PHP script  for further processing.

<?php
$clName = ($_POST['clientName']);
echo 'Hi, your Name is...' . $clName;
?>

Putting all together (I prefer separate files for HTML and PHP code)

<html>
<head>
</head>
<body>
<form action=" " method="post">
<input type="text" name="clientName"><br>
<input type="submit" value="submit">
</form>
<?php
$clName = ($_POST['clientName']);
echo 'Hi, your Name is...' . $clName;
?>
</body>
</html>

Conditional statements overview

In PHP, we have the following conditional statements :

– IF statement : executes some code only if a specified condition is true
– IF  ELSE statement : executes some code if a condition is true and another code if the condition is false
– IF   ELSE  IF   ELSE statements : selects one of several blocks of code to be executed
– SWITCH statement : selects one of many blocks of code to be executed

The IF condition

Syntax

if (condition)
{
code to be executed if condition is true;
}
else if (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if conditions are false;
}

Example 1

<?php
$age = 24;
if ($age >= 21)
{
$ majority = true;
}
else
{
$ majority = false;
}
?>

Example 1 condensed

<?php
$age = 24;
$majority = ($age >= 21) ? true : false;
?>

The SWITCH condition

We have a single expression n, most often a variable, that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed; break prevents the code from running into the next case automatically. The default statement is used if no match is found.

Syntax

switch (n)
{
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
default:
code to be executed if n is different from both label1 and label2;
}

The WHILE and the DO WHILE loop

The while loop executes a block of code while a condition is true.

Syntax

while (condition)
{
code to be executed;
}

The DO WHILE statement will always execute the block of code once, it will then check the condition and repeat the loop while the condition is true.

Syntax

do
{
code to be executed;
}
while (condition);

The FOR loop

Only when the condition is “true”, the loop will be executed.

Syntax

for (init; condition; increment)
{
code to be executed;
}

Parameters:
– init: Mostly used to set a counter (but can be any code to be executed once at the beginning of the loop)
– condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends
– increment: Mostly used to increment a counter (but can be any code to be executed at the end of the iteration)

The FOREACH loop

The FOREACH loop is used to loop through arrays.

Syntax

foreach ($array as $value)
{
code to be executed;
}

For every loop iteration, the value of the current array element is assigned to $value (and the array pointer is moved by one) – so on the next loop iteration, you’ll be looking at the next array value.

Arrays

An array is a special variable which can hold more than one value at a time.

In PHP, there are three types of arrays:
– Indexed arrays : Arrays with numeric index
– Associative arrays : Arrays with named keys
– Multidimensional arrays : Arrays containing one or more arrays

!!!! Accessing a non-existent array item can trigger errors; you may want to test arrays and array items for existence with isset before using them !!!!

Indexed arrays

– Create an empty array or clear an existing array

$cars=array();

– Write in array

1) The index can be assigned automatically (index always starts at 0)
$cars=array("Volvo","BMW","Toyota");

2) The index can be assigned manually
$cars[0]="Volvo";
$cars[1]="BMW";
$cars[2]="Toyota";

– Read from array

echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";

– Loop trough an array

<?php
$cars=array("Volvo","BMW","Toyota");
foreach ($cars as $value)
{
echo $value . "<br>";
}
?>

Associative arrays

Associative arrays are arrays that use named keys that you assign to them.

– Create an empty array or clear an existing array

$age=array();

– Write in array

1)
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");

2)
$age['Peter']="35";
$age['Ben']="37";
$age['Joe']="43";

– Read from array

echo "Peter is " . $age['Peter'] . " years old.";

– Loop trough an array

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
foreach ($age as $x=>$x_value)
{
echo $x . " has the age of " . $x_value;
echo '<br>';
}
?>

Array functions

With array functions, you can access and manipulate arrays. http://www.w3schools.com/php/php_ref_array.asp

Functions

In PHP there are more than 700 built-in functions.
Of course you have the possibility to write your own functions ! A function will be executed by calling it by its name.
It is useful to give the function a name that reflects what it does. The function name can start with a letter or underscore, but not with a number.

Syntax

function functionName()
{
code to be executed;
}

Parameters (arguments)

Parameters are specified after the function name, inside the parentheses.
See also : http://php.net/manual/en/functions.arguments.php

function doSoemthing ($var_A, $var_B)
{
statements;
}

– Passing function parameters by reference

<?php
$test = array("a"=>"Adam","b"=>"Eva","c"=>"Noa");
simpel($test);
echo $test["a"] ." ".$test["b"] ." ".$test["c"];
function simpel(&$test)
{
$test["a"] = "Foo";
$test["b"] = "Bar";
$test["c"] = "FoBar";
}
?>

The output  will be : Foo Bar FoBar

Return values

To let a function return a value, use the return statement.
PHP can only return one variable per function, use an array if you need to return multiple values.

– One return value

<?php
function add($x,$y)
{
$total=$x+$y;
return $total;
}
echo "1 + 17 = " . add(1,17);
?>

The output  will be : 1 + 17 = 18

– Multiple return values (or the array trick)

<?php
$test = array();
$ret_val = array();
function simpel()
{
$test["a"] = "Foo";
$test["b"] = "Bar";
$test["c"] = "FoBar";
return $test;
}
$ret_val = simpel();
echo $ret_val["a"] ." ".$ret_val["b"] ." ".$ret_val["c"];
?>

The output  will be : Foo Bar FoBar

Objects

An object is simply a “black box”. A “black box” is a chunk of code which is completely independent of any other code. It takes in information, processes it and returns a result. It also cooperates with other “black boxes”. You do not need to know anything concerning the internal working of the “black box”.

An object contains both data (called properties in Oo) and functions (called methods in Oo). The object properties describe the characteristics of an object while methods define what an object can do.

Classes are the blueprint (template) for an object. A class is at the top of the hierarchy in object oriented programming. Classes haves also properties and methods (inside). An object constructed by a class is called an instance of that class.

Coding basics and examples

http://www.killerphp.com/tutorials/php-objects-page-1/
https://www.codecademy.com/courses/web-beginner-en-ZQQ64/0/1
https://code.tutsplus.com/tutorials/object-oriented-php-for-beginners–net-12762
http://php.net/manual/en/classobj.examples.php

If you enjoyed this article, you can :
– get post updates by connecting to our RSS feed
– get post updates by subscribing to our e-mail list
– share on social media :