Sherif's Tech Blog

Just another guy on the Internet with a keyboard…

PHP Constructs

Basic PHP Constructs

Now that you have some fair understanding of basic syntax (expressions, operators, and statements) you should probably familiarize yourself with how this syntax is used in PHP to write useful code. This brings us to PHP constructs. A construct is just short for control structure. Unlike an expression the construct creates a flow of control in the code. Expressions are affected by the operations we conduct on them as we saw in our examples of operator precedence and associativity. The construct controls how or when statements are executed and in order to create a structure of code that effectively tackles the task the programmer aims to achieve.

echo

The most basic language construct you will run into in PHP is echo. It is used to send output to the standard output stream (commonly referred to on *nix systems as STDOUT). The construct accepts any number of expressions each separated by an argument-separator (the comma). You can also use the concatenation operator in PHP to concatenate or join one or more expressions together as a string. This construct essentially acts like a director in a movie. You provide it with a script to follow and it makes sure the actors each play their roles accordingly in order to get the finished movie on film. Lets take a look at how we can use the echo construct.

echo 'First result: ' , 1 + 2 * 3  / 4 – 5 , ' --- Second result: ' , ((1 + 2 * 3) / 4) – 5;

/*
* OUTPUT:
* First result: -2.5 --- Second result: -3.25
*/

I’ve highlighted the resulting output from this code for you in the commend right beneath it. The comment is highlighted in green by the syntax highlighter in this example.
So, lets see what would have happened if we didn’t pass each of those expressions as separate arguments to the echo construct, but instead concatenated the arguments in the example below?

echo 'First result: ' . 1 + 2 * 3  / 4 – 5 . ' --- Second result: ' . ((1 + 2 * 3) / 4) – 5;

/*
* OUTPUT:
* -8.5
*/

What the heck happened, right? We didn’t get any text at all. All we saw in the output was -8.5, which doesn’t even make sense according to the math.
Well, the problem is that echo is behaving like a construct. It is carrying out its orders (following the script), and then delivering the finished product — nothing more. We supplied a single expression that’s derived of a string, various expressions with arithmetic operators, another string, and more expressions with arithmetic operators. But we also used the concatenation operator between each of those various expressions. Remember the concatenation operator is a string operator. It operates on strings. Also we mentioned that PHP is a dynamically typed language. So if you supply an operator with data types that aren’t really compatible PHP will attempt to do some transparent translation (this is referred to as type-casting) between these data types if at all possible to give you the intended result of the operation. The break down of what happened in this code is as follows…

  • CONCAT: STRING with Operand 1 — 1 becomes a part of the string and their value becomes 0. This is because the value of any string that does not begin with numeric characters (regardless of any leading white space) is considered 0 and this string began with ‘First result: ‘
  • MULTIPLY: 2 with 3 — Value becomes 6
  • DIVIDE: 6 by 4 — Value becomes 1.5
  • ADD: 1.5 to result of CONCAT Operand — Value becomes 1.5 (essentially 1.5 + 0, because again the second string began with letters)
  • SUBTRACT: 5 from 1.5 — Value becomes -3.5
  • CONCAT: -3.5 with String — Value becomes -3.5 and 0
  • MULTIPLY: 2 by 3 — Value becomes 6
  • ADD: 6 to 1 — Value becomes 7
  • DIVIDE: 7 by 4 — Value becomes 1.75
  • CONCAT: 1.75 concatenated to STRING — Value becomes 0
  • SUBTRACT: 5 from 0 — Value becomes -5
  • ADD: -3.5 to -5 — Value becomes -8.5

If you feel confused, don’t be. This is exactly how syntax determines which combinations of these sequences of characters are structured correctly. Even though this is perfectly valid syntax doesn’t mean we expected this behavior. However, once you understand the syntax you can then expect the behavior and understand how to properly use it to achieve your desired result.

So now that we understood it… how do we fix it? We actually learned the answer to this when we discussed expressions in the last tutorial. Group the expressions using parenthesis. This will force PHP to evaluate those expressions as a whole, before it attempts to concatenate them to a string. In the first example we were concatenating ‘First result: ‘ with 1 and ‘ — Second result: ‘ with ((1 + 2 * 3) / 4) and then trying to do the math. Below we group the expressions with arithmetic operations into inner-most expression groups and then concatenate the group. So PHP sees [string], [expression], [string], [expression]

echo 'First result: ' . (1 + 2 * 3  / 4 – 5) . ' --- Second result: ' . (((1 + 2 * 3) / 4) – 5);
/* OUTPUT:
* First result: -2.5 --- Second result: -3.25
*/

Ahah! Now we achieved the same result as in the first example. The difference is that in the first example the construct received each expression individually (that’s what the commas were doing – passing one expression at a time). So it would evaluate the string first and send it to the output stream. Then it would evaluate the expression with arithmetic operations and output that — and so on and so forth. In the last example we required the construct to evaluate the entire expression as a whole before it sent anything to the output stream.

if/elseif/else

Notice we aren’t required to group expressions in parenthesis inside the echo construct. One place where the expression does have to be grouped into parenthesis is in the if construct. Also keep in mind you can group smaller expressions inside of a single expression group (so multiple expressions can make up one larger expression).

if (false) {
	echo 'It is false';
}
elseif (0) {
	echo 'It is zero';
}
else {
	echo 'It is something else...';
}

The above example demonstrates conditional statements. Everything inside of the parenthesis in this example is an expression (the ones following if, elseif, and else). And everything inside of the opening and closing curly-braces are statements (terminated by a semicolon). This is also referred to as bracketed syntax. PHP takes on many syntax styles from C and Java and these are both also bracketed languages that use similar syntax.

Basically, there can only ever be one group of statements (statements are grouped by curly-braces – like expressions are grouped by parenthesis) executed in this structure. The control is only transferred to the first group of statements whose expression evaluates to a boolean true. Remember, we discussed every expression must ultimately be evaluated to either TRUE or FALSE and this denotes our concept of truth in expression. It’s pretty obvious from this example which of these statements gets executed. FALSE, can obviously never be true (that is to say it can never contain the presence of value). We also demonstrated earlier that 0 also evaluates to a boolean false and thus there is no presence of value in this expression.

This control structure always starts with the expression in the IF clause first (and it must come first in your code). You can follow the if block with multiple elseif (secondary conditions that will each be evaluated in the order they are presented) and/or a single else block (which takes no expression and gets executed only if all the other conditions have expressions that evaluate to false).

If the first expression evaluates to true (the expression inside the if clause) it will execute the statement or statements for that condition and terminate the rest of the structure (that means it will not bother evaluating any other expression or executing any other statement in the same control-structure). If the first expression doesn’t evaluate to true it will check each of the elseif expressions (there can be one or more or none) and whichever gets evaluated to true will transfer control to their statement group and then terminate the rest of the structure. If there are no elseif conditions or none of them get evaluated to true, and there is an else condition (you may only have one or no else conditions in a single if construct) the structure simply executes the statement or group of statements in that condition without evaluating any expressions.

It is also possible to nest control structures. So you can have multiple nested if/elseif/else control structures inside of one another. This is usually not a normal case, because you tend to find that a single if construct can usually suffice as you are able to use comparison and logical operators in your conditions. Take the following example.

if (1 + 1 > 2 || 1 + 1 < 2) {
	echo '1 + 1 is either greater than or less than 2';
}
else {
	echo '1 + 1 is equal to 2';
}

/*
* OUTPUT:
* 1 + 1 is equal to 2
*/

In the above example we make a logical comparison between two expressions. The logical operator being used here is the or operator denoted by two pipes ||. There is another logical operator in PHP that is a literal ‘or‘, but it has a lesser precedence. The first expression is evaluating if 1 + 1 is greater than 2 and the second is evaluating if it is less than 2. So if either of these conditions are met (one or the other) the statement group in the if condition would transfer control there and terminate the structure. Of course neither of these conditions can be met, because 1 + 1 is exactly equal to 2. So the control structure executes the statement group in the else condition and terminates.

PHP accepts both elseif and else if as valid syntax for this control structure. So you may put a space between them or you may not and both are acceptable syntax. You may also exclude the curly-braces if each condition is only met by a single statement in the structure. However, it makes your code a lot more readable if you always use the brackets (or curly braces) even if there is only one statement.

for loops

This control structure allows you to create a loop based on three basic expressions. The for construct executes all of the statements inside of the loop. The construct takes on these three expressions in the form of for ([expression 1]; [expression 2]; [expression 3]) { [statement]… } where each expression is terminated by a semicolon and [expression 1] is evaluated only once and without condition at the start of the loop. This is where you can do variable initialization and assignment for variables you might want to use in your loop. We’ll also discuss variables in more detail in the next tutorial. The second expression [expression 2] is evaluated at the beginning of each iteration (or loop) and if it evaluates to true the loop will continue if not the construct terminates the loop at that point and returns control to the rest of the code. The third expression [expression 3] is evaluated, without condition, at the end of each loop. So lets take a look at an example of how we may use the for construct to create a loop.

for ($i = 0; $i < 10; $i ++) {
	echo $i;
}

/*
* OUTPUT:
* 0123456789
*/

In the example above we assigned (or initialized) the variable $i with the value of 0. In the second expression the construct determines if the boolean value of the expression ($i < 10) is either true or false. Meaning that the value of the variable $i must always be less than 10 in order for the statement echo $i; to be executed. The third expression is using the incremental operator denoted by two addition (or plus) signs. This operator evaluates and returns the expression to its right and then increments it by one. Since this third expression in the construct is evaluated without condition the only thing we care about here is increasing the value of $i by one at the end of each loop. This means once $i reaches the value of 10 the for construct terminates at the beginning of the next loop and returns the control to the rest of your code outside of the construct. The result is that we get the output of each value of $i throughout the loop, which is 0 through 9.

Your email address will not be published. Required fields are marked *

*