Fundamentals of PHP

2.1 Variables:

A variable can hold a value that can be changed during the course of the execution of the script. The values can either be explicitly changed or by performing some operation on it. They are similar to variables you used back in school Algebra.

Let’s look at the syntax of a PHP variable:

$variable_name = Value; Example:
<?php
$learning = “Learning Variable!”;
$x_numeral = 8;
$first_name = ‘John’;
$lastName = ‘Denver’;
$nextDecimal = 16.2;

?>
  Here, we have inserted a variable name and set the value as per our need. The second line of the program with ‘$learning’ variable ends with a semicolon sign (;) to mark the closing of the statement “Learning Variable”. The quotation mark (“ “), inserted in the second line, is not used in the second variable (‘$x_numeral) as it is an integer. PHP is a case sensitive programming language. Here ‘$x_numeral’ variable differs from the variable ‘$X_numeral’ variable differs from the variable ‘$X_numeral’ because of the use of small ‘x’ in the first variable and capital ‘X’ in the second variable. The dollar sign ($) at the beginning of the variable is important as it is exclusively used in PHP. It instructs the PHP engine that the inserted code with this dollar sign is a variable. A variable in PHP always starts with an underscore ‘_’ or with a letter (x, X). You cannot begin a variable with a number. It is a common practice to separate variable names with underscore (as in $first_name) when two or more words are used to name them, or by converting the first letter of each word to uppercase (as in $lastName). This is done simply to make the name more readable . Now let us look at the various types of variables:
  1. Integer: These are whole number(s) (-9, 9, 99, 999, etc).
  2. Double/Float: These are floating point numbers or real numbers (0.99, 99.0, etc).
  3. String: These are strings of characters (“Learn”, “Java and JavaScript”). This type of variable holds both words and sentences.
  4. Boolean: This holds only two types of data: True and False.
  5. Array: This type of variable holds a list of items. ($student = array(“class”, “section”, “roll”);
  6. Object: This is an instance of a class.
The variable can be accessed from within the ‘Variable Scope’ where it was defined. A variable cannot be accessed if it was defined in a completely different scope. There are three types of Variable Scope: Superglobal, Global and Function.
  1.   Superglobal: The Superglobal variable is a type of pre-defined array in PHP. These variables can be accessed from every section of the code.
  2.   Global: Global variables can be viewed throughout the script if these are declared in it.
  3.   Function: Local variables are declared in a function scope. These variables are exclusively ‘local’ to the function in which they are declared. These variables cannot be accessed from outside the Function where it was defined.
In PHP, there are some in-built functions that can check the authenticity of a variable. The function ‘isset()’ is used to check the existence of a variable. It returns Boolean result (True or False). To remove a variable from the memory, the ‘unset()’ function is used. The ‘empty()’ function is used to check whether a variable has been defined and holds a non-empty value.   String Literals: We have already discussed that Strings hold both words and sentences.These are always inserted within quotation marks. If it starts with a single quotation mark then it must end with the same. If a single quotation is inserted at the beginning of a string then it can not be closed with a double quotation mark. If the quotation marks are inserted in a code without any characters, then it will be treated as ‘Null’ string. A numeric character is treated as a string if it is inserted within quotation marks. For example, if the number 9 is inserted in a PHP code, then it will be treated as a number. On the other hand, if 9 is inserted in a PHP code, then it will be treated as a string. Example:
  • “It is an example of a string with double quotes”
  • ‘It is an example of a string with single quotes’
  • “It is also an example of ‘a string’ where the single quote will be ignored”
  • ‘It is an example of “a string” where the double quote will be ignored’
  • “4”
  • ““ (Null string)
  ‘Here-docs’ ‘Here-docs’ or ‘Here Documents’ is a special type of quoting that enables you to quote a large block of text within a script. Here, multiple print statements and quotation marks are not used. The PHP engine treats this block of code as a double quoted statement. ‘Here-docs’ is extremely useful when a large block of HTML is used in a PHP script. ‘Here-docs’ usually begin and end with a delimiter word, a series of one or more characters that mark the border between various sections in a data system. Numeric characters, letters and underscores can be inserted in the delimiters. In PHP, delimiters are written in capital letters. Three less than signs (<<<) are inserted at the beginning of a delimiter (Example, <<<HEREDOCS). Look at the following example: Example:
<?php

$string = <<<EOD

Example of PHP heredoc stringing

across multiple lines of stringing

learning through example of using heredoc syntax.

EOD;

?>
   

Now-docs

Now-doc is similar to Here-doc, and the only difference is that it is a single quoted string while here-doc is a double quoted string. Example:
<?php

$string = <<<’EOD’

Another example of stringing

across compound lines

by using nowdoc syntax.

EOD;

 ?>
  Escape Sequences: In PHP, a single character, headed by a back slash (\), is an Escape character. The HTML <pre> tag is used to display escape sequences in the user’s browser. The PHP engine cannot interpret the escape sequences without using the HTML<pre> tag. Escape Sequences Functions
  • \” Used to print the next character as a double quote, not as a string closer
  • \’ Used to print the next character as a single quote, not a string closer
  • \n Used to print a new line character (remember our print statements?)
  • \t Used to print a tab character \r Used to print a carriage return
  • \$ Used to print the next character as a dollar, not as part of a variable
  • \\ Used to print the next character as a backslash, not an escape character
Example:
<?php

$ExampleString = “It is an \”escpd\” string”;

$ExampleSingularString = ‘It \’will\’ act’;

$ExampleNonVariable = “I have \$zilch in Example pocket”;

$ExampleNewline = “It ends with a line return\n”;

$ExampleFile = “c:\\windows\\system32\\Examplefile.txt”;

?>
    Boolean literals: Boolean literals return only two values: true and false. As discussed, PHP is a case sensitive programming language. You can only use the defined set of Boolean values like, yes/no, on/off, 1/0, etc. Look at the syntax of the Boolean literals:
<?php

$foo = True; // assign the value TRUE to $foo

?>
    Example:
<?php

// == is an operator which test

// equality and returns a Boolean value

if ($action == “display_version”) {

echo “The version is 1.23”;

}

// this is not necessary...

if ($display_dividers == TRUE) {

echo “<hr>\n”;

}

// ...as you can simply type

if ($display_dividers) {

echo “<hr>\n”;

}

?>
    Null: Null variable is assigned the ‘NULL’ value. A PHP engine will consider a variable as NULL if you do not set it. Array: The Array variables hold multiple values.   Object: Objects are used while working with the OOPs (Object Oriented Programming Language). Beginning with PHP 5 PHP is an Object Oriented Language   Resource: The Resource variables hold references to another external resource like file handler, database object, etc.   Note : Many a times you see the term Mixed variables used in the Manual it is nothing but any of the variables like simple variable, array or object.   2.3 Operators In PHP, variables and values are performed by Operators, that is, they operate on variables and values in PHP. Look at the following expression: $z = $x + $y; In the above expression x and y are two numbers. It is clear from the above expression that it would add x with y and the sum is z. The plus sign (+) inserted between x and y is an operator (Arithmetic Operator). Operators used in PHP are categorically grouped in various sections: 1. Assignment Operators 2. Arithmetic Operators 3. Comparison Operators 4. String Operators 5. Combined Operators Now let’s discuss in detail.
  1. Assignment operators
You can use the Assignment Operator to assign a value to a variable. Often a variable is assigned a value of another variable. In this case assignment operators are used. The equal character (=) is used here. Look at the following expression: $first_var = 5; $second_var = $first_var; Here the values of both ‘$first_var’ and ‘$second_ var’ variables are assigned the same value i.e. 5.  
  1. Arithmetic operators
Look at the various Arithmetic Operators: Operators Name Function  
Operator Name Function
+ Addition This operator is used to add two values
- Subtraction This operator is used to subtract the second value from the first one
* Multiplication This operator is used to multiply two values
  Division This operator is used to divide the first value by the second value
% Modulus This operator is used to divide the first value by the second value and it returns only the remainder
    Example 01:
<?php

$adding = 2 + 4;

$minus = 6 - 2;

$multiply = 5 * 3;

$divide = 15 / 3;

$percent = 5 % 2;

echo “Result adding: 2 + 4 = “.$adding.”<br />”;

echo “Result minus: 6 - 2 = “.$minus.”<br />”;

echo “Result multiply: 5 * 3 = “.$multiply.”<br

/>”;

echo “Result divide: 15 / 3 = “.$divide.”<br />”;

echo “Result percent: 5 % 2 = “ . $percent

?>
  The output of the above program is as follows: Result adding: 2 + 4 = 6 Result minus: 6 – 2 = 4 Result multiply: 5 * 3 = 15 Result divide: 15 / 3 = 5 Result percent: 5 % 2 = 1.   Comparison operators The ‘Comparison Operators’ verify the relationship between a variable and its value. These operators are usually inserted within a conditional statement and it returns boolean values like true and false. Look at the various types of Comparison Operators:
Comparision Operator Name Function
== Equal This operator is used tocheck if the two variables hold equal values.
=== Identical This operator is used to check whether two variables hold equal valuesand the data type of them are also the same.
!= Not Equal This operator is used to check if the two variableshold unequal values.
!== Not Identical This operator is used to check for unequal valuesand for the different data types.
Less Than This operator is used to check if the value of onevariable is lesser than that of another.
Greater Than This operator is used to check if the value of onevariable is greater than that of another.
<= Less Than or Equal to This operator is used to check if the value of one variable is less than or equal to the value of another variable.
>= Greater Than or Equal to This operator is used to check if the value of onevariable is greater than or equal to the value of  another variable.
    String operators There are two types of ‘String Operators’: the Concatenating Operator (‘.’) and the Concatenating Assignment Operator (‘.=’).The Concatenating Operator joins the right and the left string into a single string. The Concatenating Assignment Operators add the argument that is placed on the right side of the equal operator with the argument placed on the left side of the ‘equal’ operator. Example:
$first_string = “Welcome”;

$second_string = “ Jack”;

$third_string = $first_string . $second_string;

echo $third_string . “!”;
  The output of the above program is as follows: Welcome Jack!   Combined operators(Shorthand Operators) As the name suggests, the Combined Operators are the combinations of different types of operators. Look at the various types of Combined Operators:
Operator Name Example
+= Addition & Equals $a += 4;
-= Subtraction & Equals $a -= 4;
*= Multiplication & Equals $a *= 4;
/= Division & Equals $a /= 4;
%= Modulus & Equals $a %= 4;
.= Concatenation & Equals $example_str.=”Welcome”;
  There are some other types of operators used in PHP. Let’s look at those: Logical operators:
Logical Operators Functions
And Checks if two or more statements are true
&& Same as And
Or Checks if at least one of two statements istrue
|| Same as Or
! Checks if a statement is not true
  Increment and decrement operators:  
Increment / Decrement Operator Name Function
 ++$value Pre-Increment This operator adds 1 to the value before processing the expression that can use it.
–$value Pre-Decrement This operator subtracts 1 from the value before  processing the expression that uses the value
$value++ Post-Increment This operator adds 1 to the value after processing the expression by which the  value can be used
$value– Post-Decrement This operator subtracts 1 from the value after processing the expression which uses the value
  2.4 Control structure The ‘Control Structure’ controls the program flow of PHP. It can also check whether a  block of code is executed or not. The syntax of the ‘Control Structure’ is as follows: <?php if (expression) statement ?> Let’s look at various types of ‘Control Structure’:
  1. if
  2. elseif/else if
  3. Alternative syntax for control structures
  4. while
  5. do-while
  6. for
  7. foreach
  8. switch
1) if: It is used for conditional execution of code. The condition in the if evaluates to  Boolean values (true/false). Look at the syntax of ‘if’ Control Structure: if (expr) statement Example:
<?php

if ($x > $y) {

echo “x is bigger than y”;

$y = $x;

}

?>
  else: If an expression in the ‘if’ statement returns false, then the ‘else’ ‘Control Structure’ is used. Example:
<?php

if ($x > $y) {

echo “x is bigger than y”;

} else {

echo “x is NOT bigger than y”;

}

?>
  elseif/else if: It is a combination of ‘if’ and ‘else’ Control Structure. If the ‘if’ Control Structure’ returns a ‘false’ value, then a different statement is executed by using the ‘else’ Control Structure’. Example:
<?php

if ($x > $y) {

echo “x is bigger than y”;

} elseif ($x == $y) {

echo “x is equal to y”;

} else {

echo “x is smaller than y”;

}

?>
  “Alternative syntax for control structures: There are some alternative syntax for some control structures like, ‘if’, ‘while’, ‘for’, ‘foreach’ and ‘switch’. It changes the opening brace to a colon sign (:) and closing brace to endif;, endwhile;, endfor;, endforeach;, or endswitch. Example:
<?php

if ($x == 6):

echo “x equals 6”;

echo “...”;

elseif ($x == 7):

echo “x equals 7”;

echo “!!!”;

else:

echo “x is neither 6 nor 7”;

endif;

?>
  while: The ‘while’ Control Structure executes the nested statements repetitively until the ‘while’ statement returns a false value. The syntax of ‘while’ control structure is as follows: while (expr) statement do-while: It is very much similar to the ‘while’ Control Structure. The only difference is that here the truth expression is checked at the end of every repetition. Look at the syntax of ‘do-while’:
<?php

$i = 0;

do {

echo $i;

} while ($i > 0);

?>
  for: This is one of the complex loops in PHP. The syntax of the ‘for’ control structure is as follows: for (expr1; expr2; expr3) statement foreach: This Control Structure is first introduced in PHP. Have a look at its syntax: foreach (array_expression as $value) statement foreach (array_expression as $key => $value) statement switch: This Control Structure is similar to a series of ‘if’ statements.