July 26, 2017

Core PHP: Include & Require (5.19)

include vs require


The require statement is identical to include, the exception being that, upon failure, it produces a fatal error.
When a file is included using the include statement, but PHP is unable to find it, the script continues to execute.
In the case of require, the script will cease execution and produce an error.

Use require when the file is required for the application to run.
Use include when the file is not required. The application should continue, even when the file is not found.

Core PHP: Include & Require (5.18)

include


Using this approach, we have the ability to include the same header.php file into multiple pages.

<html>
  <body>

  <?php include 'header.php'; ?>

  <p>This is a paragraph</p>
  </body>
</html>

Result:
Example: include


Files are included based on the file path.
You can use an absolute or a relative path to specify which file should be included.

Core PHP: Include & Require (5.17)

include


The include and require statements allow for the insertion of the content of one PHP file into another PHP file, before the server executes it.
Including files saves quite a bit of work. You can create a standard header, footer, or menu file for all of your web pages. Then, when the header is requiring updating, you can update the header include file only.

Assume that we have a standard header file called header.php.

<?php
  echo '<h1>Welcome</h1>';
?>

Use the include statement to include the header file in a page.

<html>
  <body>

  <?php include 'header.php'; ?>

  <p>Some text.</p>
  <p>Some text.</p>
  </body>
</html>

Core PHP: The continue Statement (5.16)

The continue Statement


When used within a looping structure, the continue statement allows for skipping over what remains of the current loop iteration. It then continues the execution at the condition evaluation and moves on to the beginning of the next iteration.

The following example skips the even numbers in the for loop:
for ($i=0; $i<10; $i++) {
  if ($i%2==0) {
    continue;
  }
  echo $i . ' ';
}

//Output: 1 3 5 7 9

You can use the continue statement with all looping structures.

Core PHP: The break Statement (5.15)

The break Statement


As discussed in the previous lesson, the break statement is used to break out of the switch when a case is matched.
If the break is absent, the code keeps running. For example:

$x=1;
switch ($x) {
  case 1:
    echo "One";
  case 2:
    echo "Two";
  case 3:
    echo "Three";
  default:
    echo "No match";
}

//Outputs "OneTwoThreeNo match"

Break can also be used to halt the execution of for, foreach, while, do-while structures.
The break statement ends the current for, foreach, while, do-while or switch and continues to run the program on the line coming up after the loop.
A break statement in the outer part of a program (e.g., not in a control loop) will stop the script.

Core PHP: The Switch Statement (5.14)

Switch


Failing to specify the break statement causes PHP to continue to executing the statements that follow the case, until it finds a break. You can use this behavior if you need to arrive at the same output for more than one case.
$day = 'Wed';

switch ($day) {
  case 'Mon':
    echo 'First day of the week';
    break;
  case 'Tue':
  case 'Wed':
  case 'Thu':
    echo 'Working day';
    break;
  case 'Fri':
    echo 'Friday!';
    break;
  default:
    echo 'Weekend!';
}

//Outputs "Working day"

The example above will have the same output if $day equals 'Tue', 'Wed', or 'Thu'.

Core PHP: The Switch Statement (5.13)

default


The default statement is used if no match is found.

$x=5;
switch ($x) {
  case 1:
    echo "One";
    break;
  case 2:
    echo "Two";
    break;
  default:
    echo "No match";
}

//Outputs "No match"

The default statement is optional, so it can be omitted.

Core PHP: The Switch Statement (5.12)

Switch


Consider the following example, which displays the appropriate message for each day.
$today = 'Tue';

switch ($today) {
  case "Mon":
    echo "Today is Monday.";
    break;
  case "Tue":
    echo "Today is Tuesday.";
    break;
  case "Wed":
    echo "Today is Wednesday.";
    break;
  case "Thu":
    echo "Today is Thursday.";
    break;
  case "Fri":
     echo "Today is Friday.";
     break;
  case "Sat":
     echo "Today is Saturday.";
     break;
  case "Sun":
     echo "Today is Sunday.";
     break;
  default:
     echo "Invalid day.";
}
//Outputs "Today is Tuesday."

The break keyword that follows each case is used to keep the code from automatically running into the next case. If you forget the break; statement, PHP will automatically continue through the next case statements, even when the case doesn't match.

Core PHP: The Switch Statement (5.11)

The switch Statement


The switch statement is an alternative to the if-elseif-else statement.
Use the switch statement to select one of a number of blocks of code to be executed.

Syntax:
switch (n) {
  case value1:
    //code to be executed if n=value1
    break;
  case value2:
     //code to be executed if n=value2
     break;
  ...
  default:
    // code to be executed if n is different from all labels
}

First, our single expression, n (most often a variable), is evaluated once. Next, the value of the expression is compared with the value of each case in the structure. If there is a match, the block of code associated with that case is executed.

Using nested if else statements results in similar behavior, but switch offers a more elegant and optimal solution.

July 25, 2017

Core PHP: The foreach Loop (5.10)

The foreach Loop


The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.

There are two syntaxes:

foreach (array as $value) {
  code to be executed;
}
//or
foreach (array as $key => $value) {
   code to be executed;
}

The first form loops over the array. On each iteration, the value of the current element is assigned to $value, and the array pointer is moved by one, until it reaches the last array element.
The second form will additionally assign the current element's key to the $key variable on each iteration.

The following example demonstrates a loop that outputs the values of the $names array.

$names = array("John", "David", "Amy");
foreach ($names as $name) {
   echo $name.'<br />';
}

// John
// David
// Amy

Core PHP: The For Loop (5.9)

The for Loop


The example below displays the numbers from 0 to 5:
for ($a = 0; $a < 6; $a++) {
   echo "Value of a : ". $a . "<br />";
}

Result:
Example: The for loop


The for loop in the example above first sets the variable $a to 0, then checks for the condition ($a < 6). If the condition is true, it runs the code. After that, it increments $a ($a++).

Core PHP: The For Loop (5.8)

The for Loop


The for loop is used when you know in advance how many times the script should run.
for (init; test; increment) {
   code to be executed;
}

Parameters:
init: Initialize the loop counter value
test: Evaluates each time the loop is iterated, continuing if evaluates to true, and ending if it evaluates to false
increment: Increases the loop counter value
Each of the parameter expressions can be empty or contain multiple expressions that are separated with commas.
In the for statement, the parameters are separated with semicolons.

Core PHP: The Do While Loop (5.7)

The do...while Loop


The example below will write some output, and then increment the variable $i by one. Then the condition is checked, and the loop continues to run, as long as $i is less than or equal to 7.
$i = 5;
do {
   echo "The number is " . $i . "<br/>";
   $i++;
} while($i <= 7);

//Output
//The number is 5
//The number is 6
//The number is 7

Note that in a do while loop, the condition is tested AFTER executing the statements within the loop. This means that the do while loop would execute its statements at least once, even if the condition is false the first time.

Core PHP: The Do While Loop (5.6)

The do...while Loop


The do...while loop will always execute the block of code once, check the condition, and repeat the loop as long as the specified condition is true.

Syntax:
do {
  code to be executed;
} while (condition is true);

Regardless of whether the condition is true or false, the code will be executed at least once, which could be needed in some situations.

July 24, 2017

Core PHP: The while Loop (5.5)

The while Loop

The example below first sets a variable $i to one ($i = 1). Then, the while loop runs as long as $i is less than seven ($i < 7). $i will increase by one each time the loop runs ($i++):
$i = 1;
while ($i < 7) {
  echo "The value is $i <br />";
  $i++;
}

This produces the following result:
Example: Loop

Core PHP: The while Loop (5.4)

Loops

When writing code, you may want the same block of code to run over and over again. Instead of adding several almost equal code-lines in a script, we can use loops to perform a task like this.

The while Loop

The while loop executes a block of code as long as the specified condition is true.
Syntax:
while (condition is true) {
   code to be executed;
}

If the condition never becomes false, the statement will continue to execute indefinitely.

July 15, 2017

Core PHP: The Elseif Statement (5.3)

The Elseif Statement

For example:
<?php
$age = 21;

if ($age<=13) {
   echo "Child.";
} elseif ($age>13 && $age<19) {
   echo "Teenager";
} else {
   echo "Adult";
}

//Outputs "Adult"
?>

We used the logical AND (&&) operator to combine the two conditions and check to determine whether $age is between 13 and 19.

Core PHP: The Elseif Statement (5.2)

The Elseif Statement

Use the if...elseif...else statement to specify a new condition to test, if the first condition is false.

Syntax:
if (condition) {
  code to be executed if condition is true;
} elseif (condition) {
  code to be executed if condition is true;
} else {
   code to be executed if condition is false;
}

You can add as many elseif statements as you want. Just note, that the elseif statement must begin with an if statement.

Core PHP: The If Else Statement (5.1)

If Else

The example below will output the greatest number of the two.
<?php
$x = 10;
$y = 20;
if ($x >= $y) {
   echo $x;
} else {
   echo $y;
}

// Outputs "20"
?>

Core PHP: The If Else Statement (5.0)

Conditional Statements

Conditional statements perform different actions for different decisions.
The if else statement is used to execute a certain code if a condition is true, and another code if the condition is false.
Syntax:
if (condition) {
   code to be executed if condition is true;
} else {
   code to be executed if condition is false;
}

You can also use the if statement without the else statement, if you do not need to do anything, in case the condition is false.

July 11, 2017

Core PHP: Multi-Dimensional Arrays (4.5)

Multi-Dimensional Arrays

Let's create a two-dimensional array that contains 3 arrays:
$people = array(
   'online'=>array('David', 'Amy'),
   'offline'=>array('John', 'Rob', 'Jack'),
   'away'=>array('Arthur', 'Daniel')
);

Now the two-dimensional $people array contains 3 arrays, and it has two indices: row and column.
To access the elements of the $people array, we must point to the two indices.
echo $people['online'][0]; //Outputs "David"

echo $people['away'][1]; //Outputs "Daniel"

The arrays in the multi-dimensional array can be both numeric and associative.

Core PHP: Multi-Dimensional Arrays (4.4)

Multi-Dimensional Arrays

A multi-dimensional array contains one or more arrays.

The dimension of an array indicates the number of indices you would need to select an element.
- For a two-dimensional array, you need two indices to select an element
- For a three-dimensional array, you need three indices to select an element
Arrays more than three levels deep are difficult to manage.

Core PHP: Associative Arrays (4.3)

Associative Arrays

Use the named keys to access the array's members.
$people = array("David"=>"27", "Amy"=>"21", "John"=>"42");

echo $people['Amy']; // Outputs 21"

Core PHP: Associative Arrays (4.2)

Associative Arrays

Associative arrays are arrays that use named keys that you assign to them.
There are two ways to create an associative array:
$people = array("David"=>"27", "Amy"=>"21", "John"=>"42");
// or
$people['David'] = "27";
$people['Amy'] = "21";
$people['John'] = "42";

In the first example, note the use of the => signs in assigning values to the named keys.

Core PHP: Numeric Arrays (4.1)

Numeric Arrays

You can have integers, strings, and other data types together in one array.
Example:
<?php
$myArray[0] = "John";
$myArray[1] = "<strong>PHP</strong>";
$myArray[2] = 21;

echo "$myArray[0] is $myArray[2] and knows $myArray[1]";

// Outputs "John is 21 and knows PHP"
?>

Core PHP: Numeric Arrays (4.0)

Arrays

An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of names, for example), storing them in single variables would look like this:
$name1 = "David";
$name2 = "Amy";
$name3 = "John";

But what if you have 100 names on your list? The solution: Create an array!

Numeric Arrays

Numeric or indexed arrays associate a numeric index with their values.
The index can be assigned automatically (index always starts at 0), like this:
$names = array("David", "Amy", "John");

As an alternative, you can assign your index manually.
$names[0] = "David";
$names[1] = "Amy";
$names[2] = "John";

We defined an array called $names that stores three values.
You can access the array elements through their indices.
echo $names[1]; // Outputs "Amy"

Remember that the first element in an array has the index of 0, not 1.

Core PHP: Logical Operators (3.6)

Logical Operators

Logical operators are used to combine conditional statements.

PHP: Logical Operators

Core PHP: Comparison Operators (3.5)

Comparison Operators

Additional comparison operators:
PHP: Comparison Operators

Core PHP: Comparison Operators (3.4)

Comparison Operators

Comparison operators compare two values (numbers or strings).
Comparison operators are used inside conditional statements, and evaluate to either TRUE or FALSE.

PHP: Comparison Operators

Core PHP: Assignment Operators (3.3)

Assignment Operators

Assignment operators work with numeric values to write values to variables.
$num1 = 5;
$num2 = $num1;

$num1 and $num2 now contain the value of 5.

Assignments can also be used in conjunction with arithmetic operators.
PHP: Assignment Operators


Example:
<?php
 $x = 50;
 $x += 100;
 echo $x;

 // Outputs: 150
?> 

Core PHP: Increment & Decrement (3.2)

Increment & Decrement

The increment operators are used to increment a variable's value.
The decrement operators are used to decrement a variable's value.
$x++; // equivalent to $x = $x+1;
$x--; // equivalent to $x = $x-1;

Increment and decrement operators either precede or follow a variable.
$x++; // post-increment
$x--; // post-decrement
++$x; // pre-increment
--$x; // pre-decrement

The difference is that the post-increment returns the original value before it changes the variable, while the pre-increment changes the variable first and then returns the value.
Example:
$a  = 2; $b = $a++; // $a=3,  $b=2
$a  = 2; $b = ++$a; // $a=3,  $b=3

Core PHP: Modulus (3.1)

Modulus

The modulus operator, represented by the % sign, returns the remainder of the division of the first operand by the second operand:
<?php
  $x = 14;
  $y = 3;
  echo $x % $y; // 2
?>

If you use floating point numbers with the modulus operator, they will be converted to integers before the operation.

Core PHP: Arithmetic Operators (3.0)

Operators

Operators carry out operations on variables and values.

Example: operand and operator

Arithmetic Operators

Arithmetic operators work with numeric values to perform common arithmetical operations.

Example:
<?php
  $num1 = 8;
  $num2 = 6;

  //Addition
  echo $num1 + $num2; //14

  //Subtraction
  echo $num1 - $num2; //2

  //Multiplication
  echo $num1 * $num2; //48

  //Division
   echo $num1 / $num2; //1.33333333333
?>

Core PHP: Variable Variables (2.6)

Variable Variables

With PHP, you can use one variable to specify another variable's name. 
So, a variable variable treats the value of another variable as its name.

For example:
<?php
  $a = 'hello';
  $hello = "Hi!";
  echo $$a;

  // Outputs 'Hi!'
?>

$$a is a variable that is using the value of another variable, $a, as its name. The value of $a is equal to "hello". The resulting variable is $hello, which holds the value "Hi!".

July 10, 2017

Core PHP: Variable Scope (2.5)

The global Keyword

The global keyword is used to access a global variable from within a function.
To do this, use the global keyword within the function, prior to the variables.
<?php
  $name = 'David';
  function getName() {
    global $name;
    echo $name;
  }
  getName();

  //Outputs 'David'
?>

Core PHP: Variables Scope (2.4)

Variables Scope

PHP variables can be declared anywhere in the script.
The scope of a variable is the part of the script in which the variable can be referenced or used.

PHP's most used variable scopes are local, global.
A variable declared outside a function has a global scope, and can only be accessed outside of a function.
A variable declared within a function has a local scope, and can only be accessed within that function.

Consider the following example.
<?php
  $name = 'David';
  function getName() {
    echo $name;
  }
  getName();

  // Error: Undefined variable: name
?>

This script will produce an error, as the $name variable has a global scope, and is not accessible within the getName() function.
Functions will be discussed in the coming lessons.

Core PHP: Data Types (2.3)

PHP Float

A float, or floating point number, is a number that includes a decimal point.
<?php
  $x = 42.168;
?>

PHP Boolean

A Boolean represents two possible states: TRUE or FALSE.
<?php
  $x = true; $y = false;
?>

Booleans are often used in conditional testing, which will be covered later on in the course.

Most of the data types can be used in combination with one another. In this example, string and integer are put together to determine the sum of two numbers.
<?php
  $str = "10";
  $int = 20;
  $sum = $str + $int;
  echo ($sum);

  // Outputs 30
?>

PHP automatically converts each variable to the correct data type, according to its value. This is why the variable $str is treated as a number in the addition.

Core PHP: Data Types (2.2)

Data Types

Variables can store a variety of data types.
Data types supported by PHP: String, Integer, Float, Boolean, Array, Object, NULL, Resource.

PHP String

A string is a sequence of characters, like "Hello world!"
A string can be any text within a set of single or double quotes.
<?php
  $string1 = "Hello world!"; //double quotes
  $string2 = 'Hello world!';  //single quotes
?>

You can join two strings together using the dot ( .) concatenation operator.
For example: echo $s1 . $s2


PHP Integer

An integer is a whole number (without decimals) that must fit the following criteria:
- It cannot contain commas or blanks
- It must not have a decimal point
- It can be either positive or negative
<?php
  $int1 = 42; // positive number
  $int2 = -42; // negative number
?>

Core PHP: Constants (2.1)

Constants

Constants are similar to variables except that they cannot be changed or undefined after they've been defined.
Begin the name of your constant with a letter or an underscore.
To create a constant, use the define() function:
define(name, value, case-insensitive)

Parameters:

name: Specifies the name of the constant;
value: Specifies the value of the constant;
case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false;

The example below creates a constant with a case-sensitive name:
<?php
  define("MSG", "Hi Buzz Learners!");
  echo MSG;

   // Outputs "Hi Buzz Learners!"
?>


The example below creates a constant with a case-insensitive name:
<?php
  define("MSG", " Hi Buzz Learners!", true);
  echo msg;

  // Outputs "Hi Buzz Learners!"
?>

No dollar sign ($) is necessary before the constant name.

Core PHP: Variables (2.0)

Variables

Variables are used as "containers" in which we store information.
A PHP variable starts with a dollar sign ($), which is followed by the name of the variable.
$variable_name = value;

Rules for PHP variables:
- A variable name must start with a letter or an underscore
- A variable name cannot start with a number
- A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
- Variable names are case-sensitive ($name and $NAME would be two different variables)

For example:
<?php
   $name = 'John';
   $age = 25;
   echo $name;

  // Outputs 'John'
?>
In the example above, notice that we did not have to tell PHP which data type the variable is.
PHP automatically converts the variable to the correct data type, depending on its value.
Unlike other programming languages, PHP has no command for declaring a variable. It is created the moment you first assign a value to it.

Core PHP: Comments Syntax (1.3)

Comments

In PHP code, a comment is a line that is not executed as part of the program. You can use comments to communicate to others so they understand what you're doing, or as a reminder to yourself of what you did.

A single-line comment starts with // :
<?php
echo "<p>Hello World!</p>";
// This is a single-line comment
echo "<p>I am learning PHP!</p>";
echo "<p>This is my first program!</p>";
?>

Result: 
Example: php comments

Multi-Line Comments

Multi-line comments are used for composing comments that take more than a single line.
A multi-line comment begins with /* and ends with */.
<?php
echo "<p>Hello World!</p>";
/*
This is a multi-line comment block
that spans over
multiple lines
*/
echo "<p>I am learning PHP!</p>";
echo "<p>This is my first program!</p>";
?>

Adding comments as you write your code is a good practice. It helps others understand your thinking and makes it easier for you to recall your thought processes when you refer to your code later on.

Core PHP: Echo Syntax (1.2)

Echo

PHP has a built-in "echo" function, which is used to output text.
In actuality, it's not a function; it's a language construct. As such, it does not require parentheses.

Let's output a text.
<?php
echo "I love PHP!";
?>

The text should be in single or double quotation marks.

PHP Statements

Each PHP statement must end with a semicolon.
<?php
echo "A";
echo "B";
echo "C";
?>

Forgetting to add a semicolon at the end of a statement results in an error.

HTML markup can be added to the text in the echo statement.
<?php
echo "<strong>This is a bold text.</strong>";
?>

Result: 
Example: My First PHP Page



Core PHP: Basic Syntax (1.1)

PHP Syntax

A PHP script starts with <?php and ends with ?> :
<?php
// PHP code goes here
?>
Here is an example of a simple PHP file. The PHP script uses a built in function called "echo" to output the text "Hello World!" to a web page.
<html>
<head>
<title>My First PHP Page</title>
</head>
<body>
<?php 
echo "Hello World!";
?>
</body>
</html>

PHP statements end with semicolons (;).

Alternatively, we can include PHP in the HTML <script> tag.

<html>
<head>
<title>My First PHP Page</title>
</head>
<body>
<script language="php">
echo "Hello World!";
</script>
</body>
</html>

However, the latest version of PHP removes support for <script language="php"> tags. As such, we recommend using <?php ?> exclusively.

You can also use the shorthand PHP tags, <? ?>, as long as they're supported by the server.
<?
echo "Hello World!";
?>

However, <?php ?>, as the official standard, is the recommended way of defining PHP scripts.

Core PHP: Introduction (1.0)

Welcome to PHP

PHP: Hypertext Preprocessor (PHP) is a free, highly popular, open source scripting language. PHP scripts are executed on the server.

Just a short list of what PHP is capable of:
- Generating dynamic page content
- Creating, opening, reading, writing, deleting, and closing files on the server
- Collecting form data
- Adding, deleting, and modifying information stored in your database
- controlling user-access
- encrypting data
- and much more!

Before starting this tutorial, you should have a basic understanding of HTML.
PHP has enough power to work at the core of WordPress, the busiest blogging system on the web. It also has the degree of depth required to run Facebook, the web's largest social network!

Why PHP

PHP runs on numerous, varying platforms, including Windows, Linux, Unix, Mac OS X, and so on.
PHP is compatible with almost any modern server, such as Apache, IIS, and more.
PHP supports a wide range of databases.
PHP is free!
PHP is easy to learn and runs efficiently on the server side.